<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"><title>Spring源码系列-第6章-AOP的后置处理器和代理对象的创建 | 风祈的时光录</title><meta name="keywords" content="Spring，框架，spring源码"><meta name="author" content="youthlql"><meta name="copyright" content="youthlql"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="AOP源码">
<meta property="og:type" content="article">
<meta property="og:title" content="Spring源码系列-第6章-AOP的后置处理器和代理对象的创建">
<meta property="og:url" content="https://imlql.cn/post/598f6b0d.html">
<meta property="og:site_name" content="风祈的时光录">
<meta property="og:description" content="AOP源码">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://npm.elemecdn.com/lql_static@latest/logo/spring.png">
<meta property="article:published_time" content="2022-03-19T04:01:02.000Z">
<meta property="article:modified_time" content="2022-07-24T11:22:15.036Z">
<meta property="article:author" content="youthlql">
<meta property="article:tag" content="Spring源码">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://npm.elemecdn.com/lql_static@latest/logo/spring.png"><link rel="shortcut icon" href="https://npm.elemecdn.com/youthlql@1.0.8/blog/favicon.png"><link rel="canonical" href="https://imlql.cn/post/598f6b0d"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//hm.baidu.com"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://npm.elemecdn.com/@fortawesome/fontawesome-free@6/css/all.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://npm.elemecdn.com/@fancyapps/ui/dist/fancybox.css" media="print" onload="this.media='all'"><script>var _hmt = _hmt || [];
(function() {
  var hm = document.createElement("script");
  hm.src = "https://hm.baidu.com/hm.js?f693ff99cc7e613b88cf5b729a14b48b";
  var s = document.getElementsByTagName("script")[0]; 
  s.parentNode.insertBefore(hm, s);
})();
</script><script>const GLOBAL_CONFIG = { 
  root: '/',
  algolia: undefined,
  localSearch: {"path":"search.xml","languages":{"hits_empty":"找不到您查询的内容：${query}"}},
  translate: {"defaultEncoding":2,"translateDelay":0,"msgToTraditionalChinese":"繁","msgToSimplifiedChinese":"簡"},
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":false},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '天',
  date_suffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: undefined,
  lightbox: 'fancybox',
  Snackbar: undefined,
  source: {
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery@2/dist/fjGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery@2/dist/fjGallery.min.css'
    }
  },
  isPhotoFigcaption: false,
  islazyload: true,
  isAnchor: false
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: 'Spring源码系列-第6章-AOP的后置处理器和代理对象的创建',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2022-07-24 19:22:15'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          if (t === 'dark') activateDarkMode()
          else if (t === 'light') activateLightMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const detectApple = () => {
      if(/iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
    })(window)</script><link rel="stylesheet" href="https://npm.elemecdn.com/lql_static@latest/butterfly_static/css/ali_icon.css"><link rel="stylesheet" href="https://npm.elemecdn.com/lql_static@latest/butterfly_static/css/2-24-mogai.css"><meta name="generator" content="Hexo 5.4.0"><link rel="alternate" href="/atom.xml" title="风祈的时光录" type="application/atom+xml">
</head><body><div id="web_bg"></div><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src= "" data-lazy-src="https://npm.elemecdn.com/lql_static@latest/avatar/2.jpg" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="site-data is-center"><div class="data-item"><a href="/archives/"><div class="headline">文章</div><div class="length-num">37</div></a></div><div class="data-item"><a href="/tags/"><div class="headline">标签</div><div class="length-num">21</div></a></div><div class="data-item"><a href="/categories/"><div class="headline">分类</div><div class="length-num">13</div></a></div></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw iconfont icon-shouyex"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);"><i class="fa-fw iconfont icon-zuixinwenzhang_huaban"></i><span> 找文章</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/categories/"><i class="fa-fw iconfont icon-fenlei1"></i><span> 分类</span></a></li><li><a class="site-page child" href="/tags/"><i class="fa-fw iconfont icon-biaoqian1"></i><span> 标签</span></a></li><li><a class="site-page child" href="/archives/"><i class="fa-fw iconfont icon-shijianzhou"></i><span> 归档</span></a></li></ul></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url('https://npm.elemecdn.com/lql_static@latest/logo/spring.png')"><nav id="nav"><span id="blog_name"><a id="site-name" href="/">风祈的时光录</a></span><div id="menus"><div id="search-button"><a class="site-page social-icon search"><i class="fas fa-search fa-fw"></i><span> 搜索</span></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw iconfont icon-shouyex"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);"><i class="fa-fw iconfont icon-zuixinwenzhang_huaban"></i><span> 找文章</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/categories/"><i class="fa-fw iconfont icon-fenlei1"></i><span> 分类</span></a></li><li><a class="site-page child" href="/tags/"><i class="fa-fw iconfont icon-biaoqian1"></i><span> 标签</span></a></li><li><a class="site-page child" href="/archives/"><i class="fa-fw iconfont icon-shijianzhou"></i><span> 归档</span></a></li></ul></div></div><div id="toggle-menu"><a class="site-page"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">Spring源码系列-第6章-AOP的后置处理器和代理对象的创建</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2022-03-19T04:01:02.000Z" title="发表于 2022-03-19 12:01:02">2022-03-19</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2022-07-24T11:22:15.036Z" title="更新于 2022-07-24 19:22:15">2022-07-24</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/Spring/">Spring</a><i class="fas fa-angle-right post-meta-separator"></i><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/Spring/%E6%BA%90%E7%A0%81V1/">源码V1</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-wordcount"><i class="far fa-file-word fa-fw post-meta-icon"></i><span class="post-meta-label">字数总计:</span><span class="word-count">8.4k</span><span class="post-meta-separator">|</span><i class="far fa-clock fa-fw post-meta-icon"></i><span class="post-meta-label">阅读时长:</span><span>40分钟</span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><h1 id="第6章-AOP的后置处理器和代理对象的创建"><a href="#第6章-AOP的后置处理器和代理对象的创建" class="headerlink" title="第6章-AOP的后置处理器和代理对象的创建"></a>第6章-AOP的后置处理器和代理对象的创建</h1><h2 id="测试类"><a href="#测试类" class="headerlink" title="测试类"></a>测试类</h2><h3 id="MainConfig"><a href="#MainConfig" class="headerlink" title="MainConfig"></a>MainConfig</h3><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="meta">@ComponentScan(&quot;cn.imlql.spring&quot;)</span></span><br><span class="line"><span class="meta">@Configuration</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">MainConfig</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">   <span class="function"><span class="keyword">public</span> <span class="title">MainConfig</span><span class="params">()</span></span>&#123;</span><br><span class="line">      System.out.println(<span class="string">&quot;MainConfig...创建了....&quot;</span>);</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="AopOpenConfig"><a href="#AopOpenConfig" class="headerlink" title="AopOpenConfig"></a>AopOpenConfig</h3><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="meta">@EnableAspectJAutoProxy</span> <span class="comment">//开启自动代理</span></span><br><span class="line"><span class="meta">@Configuration</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">AopOpenConfig</span> </span>&#123;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="LogAspect"><a href="#LogAspect" class="headerlink" title="LogAspect"></a>LogAspect</h3><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * </span></span><br><span class="line"><span class="comment"> * 正常：前置通知===目标方法===返回通知===后置通知</span></span><br><span class="line"><span class="comment"> * 异常: 前置通知===目标方法===异常通知===后置通知</span></span><br><span class="line"><span class="comment"> * try&#123;</span></span><br><span class="line"><span class="comment"> *     前置通知</span></span><br><span class="line"><span class="comment"> *     目标方法的执行</span></span><br><span class="line"><span class="comment"> *     返回通知</span></span><br><span class="line"><span class="comment"> * &#125;catch()&#123;</span></span><br><span class="line"><span class="comment"> *     异常通知</span></span><br><span class="line"><span class="comment"> * &#125;finally&#123;</span></span><br><span class="line"><span class="comment"> *     后置通知</span></span><br><span class="line"><span class="comment"> * &#125;</span></span><br><span class="line"><span class="comment"> *</span></span><br><span class="line"><span class="comment"> *</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="meta">@Component</span>  <span class="comment">//切面也是容器中的组件</span></span><br><span class="line"><span class="meta">@Aspect</span> <span class="comment">//说明这是切面</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">LogAspect</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">   <span class="function"><span class="keyword">public</span> <span class="title">LogAspect</span><span class="params">()</span></span>&#123;</span><br><span class="line">      System.out.println(<span class="string">&quot;LogAspect...&quot;</span>);</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">   <span class="comment">//前置通知  增强方法/增强器</span></span><br><span class="line">   <span class="meta">@Before(&quot;execution(* cn.imlql.spring.aop.HelloService.sayHello(..))&quot;)</span></span><br><span class="line">   <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">logStart</span><span class="params">(JoinPoint joinPoint)</span></span>&#123;</span><br><span class="line">      String name = joinPoint.getSignature().getName();</span><br><span class="line">      System.out.println(<span class="string">&quot;logStart()==&gt;&quot;</span>+name+<span class="string">&quot;....【args: &quot;</span>+ Arrays.asList(joinPoint.getArgs()) +<span class="string">&quot;】&quot;</span>);</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">   <span class="comment">//返回通知</span></span><br><span class="line">   <span class="meta">@AfterReturning(value = &quot;execution(* cn.imlql.spring.aop.HelloService.sayHello(..))&quot;,returning = &quot;result&quot;)</span></span><br><span class="line">   <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">logReturn</span><span class="params">(JoinPoint joinPoint,Object result)</span></span>&#123;</span><br><span class="line">      String name = joinPoint.getSignature().getName();</span><br><span class="line">      System.out.println(<span class="string">&quot;logReturn()==&gt;&quot;</span>+name+<span class="string">&quot;....【args: &quot;</span>+ Arrays.asList(joinPoint.getArgs()) +<span class="string">&quot;】【result: &quot;</span>+result+<span class="string">&quot;】&quot;</span>);</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">   <span class="comment">//后置通知</span></span><br><span class="line">   <span class="meta">@After(&quot;execution(* cn.imlql.spring.aop.HelloService.sayHello(..))&quot;)</span></span><br><span class="line">   <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">logEnd</span><span class="params">(JoinPoint joinPoint)</span></span>&#123;</span><br><span class="line">      String name = joinPoint.getSignature().getName();</span><br><span class="line">      System.out.println(<span class="string">&quot;logEnd()==&gt;&quot;</span>+name+<span class="string">&quot;....【args: &quot;</span>+ Arrays.asList(joinPoint.getArgs()) +<span class="string">&quot;】&quot;</span>);</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">   <span class="comment">//异常</span></span><br><span class="line">   <span class="meta">@AfterThrowing(value = &quot;execution(* cn.imlql.spring.aop.HelloService.sayHello(..))&quot;,throwing = &quot;e&quot;)</span></span><br><span class="line">   <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">logError</span><span class="params">(JoinPoint joinPoint,Exception e)</span></span>&#123;</span><br><span class="line">      String name = joinPoint.getSignature().getName();</span><br><span class="line">      System.out.println(<span class="string">&quot;logError()==&gt;&quot;</span>+name+<span class="string">&quot;....【args: &quot;</span>+ Arrays.asList(joinPoint.getArgs()) +<span class="string">&quot;】【exception: &quot;</span>+e+<span class="string">&quot;】&quot;</span>);</span><br><span class="line">   &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="HelloService"><a href="#HelloService" class="headerlink" title="HelloService"></a>HelloService</h3><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="meta">@Component</span>  <span class="comment">//切面存在的化就会返回代理对象</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">HelloService</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">   <span class="function"><span class="keyword">public</span> <span class="title">HelloService</span><span class="params">()</span></span>&#123;</span><br><span class="line">      System.out.println(<span class="string">&quot;....&quot;</span>);</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">   <span class="function"><span class="keyword">public</span> String <span class="title">sayHello</span><span class="params">(String name)</span></span>&#123;</span><br><span class="line">      String result = <span class="string">&quot;你好：&quot;</span>+name;</span><br><span class="line">      System.out.println(result);</span><br><span class="line">      <span class="keyword">int</span> length = name.length();</span><br><span class="line">      <span class="keyword">return</span> result + <span class="string">&quot;---&quot;</span> + length;</span><br><span class="line">   &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="AnnotationMainTest"><a href="#AnnotationMainTest" class="headerlink" title="AnnotationMainTest"></a>AnnotationMainTest</h3><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">package</span> cn.imlql.spring;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> cn.imlql.spring.aop.HelloService;</span><br><span class="line"><span class="keyword">import</span> cn.imlql.spring.config.MainConfig;</span><br><span class="line"><span class="keyword">import</span> org.springframework.context.ApplicationContext;</span><br><span class="line"><span class="keyword">import</span> org.springframework.context.annotation.AnnotationConfigApplicationContext;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 注解版Spring的用法</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">AnnotationMainTest</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">   <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">      ApplicationContext applicationContext =</span><br><span class="line">            <span class="keyword">new</span> AnnotationConfigApplicationContext(MainConfig.class);</span><br><span class="line"></span><br><span class="line">      <span class="comment">//AOP,原理测试</span></span><br><span class="line">      HelloService helloService = applicationContext.getBean(HelloService.class);</span><br><span class="line">      helloService.sayHello(<span class="string">&quot;zhangsan&quot;</span>);</span><br><span class="line">   &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="如何分析Spring的一个新功能"><a href="#如何分析Spring的一个新功能" class="headerlink" title="如何分析Spring的一个新功能"></a>如何分析Spring的一个新功能</h2><p>对于一个Spring的新功能我们应该按照下面的思路分析：这个功能加入哪些组件？这些组件在生命周期期间做了什么？</p>
<ol>
<li>比如我们分析AOP<ol>
<li>分析AOP给容器添加了哪些组件，分析方法如下<ol>
<li><strong>第一种方法：</strong>之前讲过的给AbstractBeanDefinition三个构造器打断点，因为绝大多数组件都是要先经过Bean定义信息的。但也不排除Spring直接new组件注册进去，不经过AbstractBeanDefinition（很少很少）。所以此时再给容器刷新refresh()方法的最后一步finishRefresh()打个断点，看容器里此时有哪些组件即可。</li>
<li><strong>第二种方法</strong>：Spring每开启一个功能，要么写配置要么写注解。Spring就要解析这些注解或者配置，Spring里面会有很多@EnableXXX这样的注解，顾名思义，就是开启什么什么功能。分析这种注解即可@EnableXXX，一般来说新功能大概率都是通过后置处理器做的，@EnableXXX肯定也是引入了新的后置处理器。</li>
</ol>
</li>
<li>这些组件在生命周期期间做了什么事。</li>
</ol>
</li>
</ol>
<h2 id="分析-EnableXXX找到负责AOP功能的后置处理器"><a href="#分析-EnableXXX找到负责AOP功能的后置处理器" class="headerlink" title="分析@EnableXXX找到负责AOP功能的后置处理器"></a>分析@EnableXXX找到负责AOP功能的后置处理器</h2><h3 id="EnableAspectJAutoProxy"><a href="#EnableAspectJAutoProxy" class="headerlink" title="@EnableAspectJAutoProxy"></a>@EnableAspectJAutoProxy</h3><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="meta">@Target(ElementType.TYPE)</span></span><br><span class="line"><span class="meta">@Retention(RetentionPolicy.RUNTIME)</span></span><br><span class="line"><span class="meta">@Documented</span></span><br><span class="line"><span class="meta">@Import(AspectJAutoProxyRegistrar.class)</span> <span class="comment">//最核心的就是这个@Import了，导入了什么组件</span></span><br><span class="line"><span class="keyword">public</span> <span class="meta">@interface</span> EnableAspectJAutoProxy &#123;</span><br><span class="line"></span><br><span class="line">   <span class="comment">/**</span></span><br><span class="line"><span class="comment">    * Indicate whether subclass-based (CGLIB) proxies are to be created as opposed</span></span><br><span class="line"><span class="comment">    * to standard Java interface-based proxies. The default is &#123;<span class="doctag">@code</span> false&#125;.</span></span><br><span class="line"><span class="comment">    */</span></span><br><span class="line">   <span class="function"><span class="keyword">boolean</span> <span class="title">proxyTargetClass</span><span class="params">()</span> <span class="keyword">default</span> <span class="keyword">false</span></span>;</span><br><span class="line"></span><br><span class="line">   <span class="comment">/**</span></span><br><span class="line"><span class="comment">    * Indicate that the proxy should be exposed by the AOP framework as a &#123;<span class="doctag">@code</span> ThreadLocal&#125;</span></span><br><span class="line"><span class="comment">    * for retrieval via the &#123;<span class="doctag">@link</span> org.springframework.aop.framework.AopContext&#125; class.</span></span><br><span class="line"><span class="comment">    * Off by default, i.e. no guarantees that &#123;<span class="doctag">@code</span> AopContext&#125; access will work.</span></span><br><span class="line"><span class="comment">    * <span class="doctag">@since</span> 4.3.1</span></span><br><span class="line"><span class="comment">    */</span></span><br><span class="line">   <span class="function"><span class="keyword">boolean</span> <span class="title">exposeProxy</span><span class="params">()</span> <span class="keyword">default</span> <span class="keyword">false</span></span>;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h4 id="AspectJAutoProxyRegistrar-registerBeanDefinitions"><a href="#AspectJAutoProxyRegistrar-registerBeanDefinitions" class="headerlink" title="AspectJAutoProxyRegistrar#registerBeanDefinitions()"></a>AspectJAutoProxyRegistrar#registerBeanDefinitions()</h4><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">AspectJAutoProxyRegistrar</span> <span class="keyword">implements</span> <span class="title">ImportBeanDefinitionRegistrar</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">   <span class="comment">/**</span></span><br><span class="line"><span class="comment">    * Register, escalate, and configure the AspectJ auto proxy creator based on the value</span></span><br><span class="line"><span class="comment">    * of the @&#123;<span class="doctag">@link</span> EnableAspectJAutoProxy#proxyTargetClass()&#125; attribute on the importing</span></span><br><span class="line"><span class="comment">    * &#123;<span class="doctag">@code</span> <span class="doctag">@Configuration</span>&#125; class.</span></span><br><span class="line"><span class="comment">    */</span></span><br><span class="line">   <span class="meta">@Override</span></span><br><span class="line">   <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">registerBeanDefinitions</span><span class="params">(</span></span></span><br><span class="line"><span class="function"><span class="params">         AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry)</span> </span>&#123;</span><br><span class="line">      <span class="comment">//注册切面的基于注解的自动代理创建器</span></span><br><span class="line">      AopConfigUtils.registerAspectJAnnotationAutoProxyCreatorIfNecessary(registry); <span class="comment">//pos_1 在这里打个断点分析一下</span></span><br><span class="line"></span><br><span class="line">      AnnotationAttributes enableAspectJAutoProxy =</span><br><span class="line">            AnnotationConfigUtils.attributesFor(importingClassMetadata, EnableAspectJAutoProxy.class);</span><br><span class="line">      <span class="keyword">if</span> (enableAspectJAutoProxy != <span class="keyword">null</span>) &#123;</span><br><span class="line">         <span class="keyword">if</span> (enableAspectJAutoProxy.getBoolean(<span class="string">&quot;proxyTargetClass&quot;</span>)) &#123;</span><br><span class="line">            AopConfigUtils.forceAutoProxyCreatorToUseClassProxying(registry);</span><br><span class="line">         &#125;</span><br><span class="line">         <span class="keyword">if</span> (enableAspectJAutoProxy.getBoolean(<span class="string">&quot;exposeProxy&quot;</span>)) &#123;</span><br><span class="line">            AopConfigUtils.forceAutoProxyCreatorToExposeProxy(registry);</span><br><span class="line">         &#125;</span><br><span class="line">      &#125;</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h3 id="Debug调用栈"><a href="#Debug调用栈" class="headerlink" title="Debug调用栈"></a>Debug调用栈</h3><img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_06/image-20211010202000109.png"/>

<h3 id="ImportBeanDefinitionRegistrar"><a href="#ImportBeanDefinitionRegistrar" class="headerlink" title="ImportBeanDefinitionRegistrar"></a>ImportBeanDefinitionRegistrar</h3><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">default</span> <span class="keyword">void</span> <span class="title">registerBeanDefinitions</span><span class="params">(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry,</span></span></span><br><span class="line"><span class="function"><span class="params">      BeanNameGenerator importBeanNameGenerator)</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">   registerBeanDefinitions(importingClassMetadata, registry);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>最后就是这样的一个调用实现类</p>
<h3 id="AopConfigUtils-registerAspectJAnnotationAutoProxyCreatorIfNecessary注册切面的基于注解的自动代理创建器"><a href="#AopConfigUtils-registerAspectJAnnotationAutoProxyCreatorIfNecessary注册切面的基于注解的自动代理创建器" class="headerlink" title="AopConfigUtils#registerAspectJAnnotationAutoProxyCreatorIfNecessary注册切面的基于注解的自动代理创建器"></a>AopConfigUtils#registerAspectJAnnotationAutoProxyCreatorIfNecessary注册切面的基于注解的自动代理创建器</h3><p>pos_1 Debug进去是下面的方法</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line">	<span class="meta">@Nullable</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> BeanDefinition <span class="title">registerAspectJAnnotationAutoProxyCreatorIfNecessary</span><span class="params">(BeanDefinitionRegistry registry)</span> </span>&#123;</span><br><span class="line">	<span class="keyword">return</span> registerAspectJAnnotationAutoProxyCreatorIfNecessary(registry, <span class="keyword">null</span>);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="meta">@Nullable</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> BeanDefinition <span class="title">registerAspectJAnnotationAutoProxyCreatorIfNecessary</span><span class="params">(</span></span></span><br><span class="line"><span class="function"><span class="params">		BeanDefinitionRegistry registry, <span class="meta">@Nullable</span> Object source)</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">	<span class="keyword">return</span> registerOrEscalateApcAsRequired(AnnotationAwareAspectJAutoProxyCreator.class, registry, source);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">final</span> String AUTO_PROXY_CREATOR_BEAN_NAME = <span class="string">&quot;org.springframework.aop.config.internalAutoProxyCreator&quot;</span>;</span><br><span class="line"></span><br><span class="line">   <span class="meta">@Nullable</span></span><br><span class="line">   <span class="function"><span class="keyword">private</span> <span class="keyword">static</span> BeanDefinition <span class="title">registerOrEscalateApcAsRequired</span><span class="params">(</span></span></span><br><span class="line"><span class="function"><span class="params">         Class&lt;?&gt; cls, BeanDefinitionRegistry registry, <span class="meta">@Nullable</span> Object source)</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">      Assert.notNull(registry, <span class="string">&quot;BeanDefinitionRegistry must not be null&quot;</span>);</span><br><span class="line"></span><br><span class="line">      <span class="keyword">if</span> (registry.containsBeanDefinition(AUTO_PROXY_CREATOR_BEAN_NAME)) &#123;</span><br><span class="line">         BeanDefinition apcDefinition = registry.getBeanDefinition(AUTO_PROXY_CREATOR_BEAN_NAME);</span><br><span class="line">         <span class="keyword">if</span> (!cls.getName().equals(apcDefinition.getBeanClassName())) &#123;</span><br><span class="line">            <span class="keyword">int</span> currentPriority = findPriorityForClass(apcDefinition.getBeanClassName());</span><br><span class="line">            <span class="keyword">int</span> requiredPriority = findPriorityForClass(cls);</span><br><span class="line">            <span class="keyword">if</span> (currentPriority &lt; requiredPriority) &#123;</span><br><span class="line">               apcDefinition.setBeanClassName(cls.getName());</span><br><span class="line">            &#125;</span><br><span class="line">         &#125;</span><br><span class="line">         <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">      &#125;</span><br><span class="line"></span><br><span class="line">      RootBeanDefinition beanDefinition = <span class="keyword">new</span> RootBeanDefinition(cls);</span><br><span class="line">      beanDefinition.setSource(source);</span><br><span class="line">      beanDefinition.getPropertyValues().add(<span class="string">&quot;order&quot;</span>, Ordered.HIGHEST_PRECEDENCE);</span><br><span class="line">      beanDefinition.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);</span><br><span class="line">      registry.registerBeanDefinition(AUTO_PROXY_CREATOR_BEAN_NAME, beanDefinition);</span><br><span class="line">      <span class="keyword">return</span> beanDefinition;</span><br><span class="line">   &#125;</span><br></pre></td></tr></table></figure>

<p>主要的就是注册了这个AnnotationAwareAspectJAutoProxyCreator组件</p>
<h3 id="AnnotationAwareAspectJAutoProxyCreator后置处理器"><a href="#AnnotationAwareAspectJAutoProxyCreator后置处理器" class="headerlink" title="AnnotationAwareAspectJAutoProxyCreator后置处理器"></a>AnnotationAwareAspectJAutoProxyCreator后置处理器</h3><img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_06/image-20211010202725286.png"/>

<p>我们发现这就是一个后置处理器，印证了我们之前说过的几乎所有功能增强或功能附加都是由后置处理器来完成</p>
<h2 id="AnnotationAwareAspectJAutoProxyCreator在生命周期期间做了什么事？"><a href="#AnnotationAwareAspectJAutoProxyCreator在生命周期期间做了什么事？" class="headerlink" title="AnnotationAwareAspectJAutoProxyCreator在生命周期期间做了什么事？"></a>AnnotationAwareAspectJAutoProxyCreator在生命周期期间做了什么事？</h2><h3 id="怎么分析？"><a href="#怎么分析？" class="headerlink" title="怎么分析？"></a>怎么分析？</h3><ol>
<li>给getBean设置一个条件断点，条件就是BeanName==AnnotationAwareAspectJAutoProxyCreator的时候</li>
<li>给AnnotationAwareAspectJAutoProxyCreator重写的父类的所有方法打上断点，因为它的最顶层接口是BeanPostProcessor 。最终肯定会一层一层往下调实现类实现的方法，大概率会调到AnnotationAwareAspectJAutoProxyCreator重写的方法。当然也不是绝对的，如果debug的时候发现没有停留，那就可以把所有方法都打上断点。或者你看方法名猜一下。</li>
<li>我们这里是两个都做了</li>
</ol>
<h3 id="负责AOP功能的后置处理器第一次运行准备好数据"><a href="#负责AOP功能的后置处理器第一次运行准备好数据" class="headerlink" title="负责AOP功能的后置处理器第一次运行准备好数据"></a>负责AOP功能的后置处理器第一次运行准备好数据</h3><h4 id="Debug调用栈-调用AnnotationAwareAspectJAutoProxyCreator的initBeanFactory-方法初始化AnnotationAwareAspectJAutoProxyCreator相关属性"><a href="#Debug调用栈-调用AnnotationAwareAspectJAutoProxyCreator的initBeanFactory-方法初始化AnnotationAwareAspectJAutoProxyCreator相关属性" class="headerlink" title="Debug调用栈-调用AnnotationAwareAspectJAutoProxyCreator的initBeanFactory()方法初始化AnnotationAwareAspectJAutoProxyCreator相关属性"></a>Debug调用栈-调用AnnotationAwareAspectJAutoProxyCreator的initBeanFactory()方法初始化AnnotationAwareAspectJAutoProxyCreator相关属性</h4><h5 id="作用"><a href="#作用" class="headerlink" title="作用"></a>作用</h5><img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_06/image-20211011222513844.png"/>

<ol>
<li>由于它是后置处理器所以肯定是在refresh方法里的registerBeanPostProcessors这一步开始干活的</li>
<li>果然是从getBean调用到了我们的重写方法断点处，也就验证了我们上面说怎么分析。绿色包含的前面已经讲过，不再赘述。</li>
<li>也确实是AnnotationAwareAspectJAutoProxyCreator，走到这里说明前面已经创建出了AnnotationAwareAspectJAutoProxyCreator对象(前面怎么创建的,getbean的流程之前已经讲的很清楚了)，后面只是对AnnotationAwareAspectJAutoProxyCreator进行初始化</li>
</ol>
<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_06/image-20211011225209123.png" />

<h5 id="AbstractAutowireCapableBeanFactory-initializeBean-进行初始化"><a href="#AbstractAutowireCapableBeanFactory-initializeBean-进行初始化" class="headerlink" title="AbstractAutowireCapableBeanFactory#initializeBean()进行初始化"></a>AbstractAutowireCapableBeanFactory#initializeBean()进行初始化</h5><p>注意此时这个参数bean就是AnnotationAwareAspectJAutoProxyCreator对象，往后走的过程中不要忘记</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line">   <span class="function"><span class="keyword">protected</span> Object <span class="title">initializeBean</span><span class="params">(String beanName, Object bean, <span class="meta">@Nullable</span> RootBeanDefinition mbd)</span> </span>&#123;</span><br><span class="line">      <span class="keyword">if</span> (System.getSecurityManager() != <span class="keyword">null</span>) &#123;</span><br><span class="line">         AccessController.doPrivileged((PrivilegedAction&lt;Object&gt;) () -&gt; &#123;</span><br><span class="line">            invokeAwareMethods(beanName, bean);</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">         &#125;, getAccessControlContext());</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="keyword">else</span> &#123;</span><br><span class="line">         invokeAwareMethods(beanName, bean); <span class="comment">//组件有Aware接口，先Aware;BeanNameAware、BeanClassLoaderAware、BeanFactoryAware</span></span><br><span class="line">      &#125;</span><br><span class="line"></span><br><span class="line">      Object wrappedBean = bean;</span><br><span class="line">      <span class="keyword">if</span> (mbd == <span class="keyword">null</span> || !mbd.isSynthetic()) &#123;<span class="comment">//执行后置处理器的BeforeInitialization方法</span></span><br><span class="line">         wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);</span><br><span class="line">      &#125;</span><br><span class="line"></span><br><span class="line">      <span class="keyword">try</span> &#123;</span><br><span class="line">         invokeInitMethods(beanName, wrappedBean, mbd);</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="keyword">catch</span> (Throwable ex) &#123;</span><br><span class="line">         <span class="keyword">throw</span> <span class="keyword">new</span> BeanCreationException(</span><br><span class="line">               (mbd != <span class="keyword">null</span> ? mbd.getResourceDescription() : <span class="keyword">null</span>),</span><br><span class="line">               beanName, <span class="string">&quot;Invocation of init method failed&quot;</span>, ex);</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="keyword">if</span> (mbd == <span class="keyword">null</span> || !mbd.isSynthetic()) &#123; <span class="comment">//</span></span><br><span class="line">         wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);</span><br><span class="line">      &#125;</span><br><span class="line"></span><br><span class="line">      <span class="keyword">return</span> wrappedBean;</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">invokeAwareMethods</span><span class="params">(String beanName, Object bean)</span> </span>&#123;</span><br><span class="line">	<span class="keyword">if</span> (bean <span class="keyword">instanceof</span> Aware) &#123;</span><br><span class="line">		<span class="keyword">if</span> (bean <span class="keyword">instanceof</span> BeanNameAware) &#123;</span><br><span class="line">			((BeanNameAware) bean).setBeanName(beanName);</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="keyword">if</span> (bean <span class="keyword">instanceof</span> BeanClassLoaderAware) &#123;</span><br><span class="line">			ClassLoader bcl = getBeanClassLoader();</span><br><span class="line">			<span class="keyword">if</span> (bcl != <span class="keyword">null</span>) &#123;</span><br><span class="line">				((BeanClassLoaderAware) bean).setBeanClassLoader(bcl);</span><br><span class="line">			&#125;</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="keyword">if</span> (bean <span class="keyword">instanceof</span> BeanFactoryAware) &#123;</span><br><span class="line">			((BeanFactoryAware) bean).setBeanFactory(AbstractAutowireCapableBeanFactory.<span class="keyword">this</span>);</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h5 id="AbstractAdvisorAutoProxyCreator-setBeanFactory"><a href="#AbstractAdvisorAutoProxyCreator-setBeanFactory" class="headerlink" title="AbstractAdvisorAutoProxyCreator#setBeanFactory()"></a>AbstractAdvisorAutoProxyCreator#setBeanFactory()</h5><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="meta">@Override</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setBeanFactory</span><span class="params">(BeanFactory beanFactory)</span> </span>&#123;</span><br><span class="line">   <span class="keyword">super</span>.setBeanFactory(beanFactory);</span><br><span class="line">   <span class="keyword">if</span> (!(beanFactory <span class="keyword">instanceof</span> ConfigurableListableBeanFactory)) &#123;</span><br><span class="line">      <span class="keyword">throw</span> <span class="keyword">new</span> IllegalArgumentException(</span><br><span class="line">            <span class="string">&quot;AdvisorAutoProxyCreator requires a ConfigurableListableBeanFactory: &quot;</span> + beanFactory);</span><br><span class="line">   &#125;</span><br><span class="line">   initBeanFactory((ConfigurableListableBeanFactory) beanFactory); <span class="comment">//子类会继续重写</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h5 id="AnnotationAwareAspectJAutoProxyCreator-initBeanFactory"><a href="#AnnotationAwareAspectJAutoProxyCreator-initBeanFactory" class="headerlink" title="AnnotationAwareAspectJAutoProxyCreator#initBeanFactory()"></a>AnnotationAwareAspectJAutoProxyCreator#initBeanFactory()</h5><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="meta">@Override</span>   <span class="comment">// BeanFactoryAware 来的。 当前后置处理器初始化创建对象的时候回调的</span></span><br><span class="line"><span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">initBeanFactory</span><span class="params">(ConfigurableListableBeanFactory beanFactory)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">super</span>.initBeanFactory(beanFactory);</span><br><span class="line">    <span class="keyword">if</span> (<span class="keyword">this</span>.aspectJAdvisorFactory == <span class="keyword">null</span>) &#123;</span><br><span class="line">        <span class="comment">// </span></span><br><span class="line">        <span class="keyword">this</span>.aspectJAdvisorFactory = <span class="keyword">new</span> ReflectiveAspectJAdvisorFactory(beanFactory); <span class="comment">//准备一个ReflectiveAspectJAdvisorFactory</span></span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">this</span>.aspectJAdvisorsBuilder =</span><br><span class="line">        <span class="keyword">new</span> BeanFactoryAspectJAdvisorsBuilderAdapter(beanFactory, <span class="keyword">this</span>.aspectJAdvisorFactory);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_06/image-20211011223856339.png" />

<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="title">ReflectiveAspectJAdvisorFactory</span><span class="params">(<span class="meta">@Nullable</span> BeanFactory beanFactory)</span> </span>&#123;</span><br><span class="line">   <span class="keyword">this</span>.beanFactory = beanFactory;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h5 id="AnnotationAwareAspectJAutoProxyCreator后置处理器创建并初始化完成"><a href="#AnnotationAwareAspectJAutoProxyCreator后置处理器创建并初始化完成" class="headerlink" title="AnnotationAwareAspectJAutoProxyCreator后置处理器创建并初始化完成"></a>AnnotationAwareAspectJAutoProxyCreator后置处理器创建并初始化完成</h5><blockquote>
<p>自此AnnotationAwareAspectJAutoProxyCreator这个后置处理器的对象已经创建完成，并且已经初始化完成。后续它就<strong>有可能</strong>要开始参与其它Bean的创建过程了。</p>
</blockquote>
<h3 id="createBean-里调用resolveBeforeInstantiation-，AnnotationAwareAspectJAutoProxyCreator后置处理器开始第一次发挥作用"><a href="#createBean-里调用resolveBeforeInstantiation-，AnnotationAwareAspectJAutoProxyCreator后置处理器开始第一次发挥作用" class="headerlink" title="createBean()里调用resolveBeforeInstantiation()，AnnotationAwareAspectJAutoProxyCreator后置处理器开始第一次发挥作用"></a>createBean()里调用resolveBeforeInstantiation()，AnnotationAwareAspectJAutoProxyCreator后置处理器开始第一次发挥作用</h3><h4 id="Debug调用栈-调用AnnotationAwareAspectJAutoProxyCreator的isInfrastructureClass-开始参与其它Bean的创建，并判断当前Bean是不是切面"><a href="#Debug调用栈-调用AnnotationAwareAspectJAutoProxyCreator的isInfrastructureClass-开始参与其它Bean的创建，并判断当前Bean是不是切面" class="headerlink" title="Debug调用栈-调用AnnotationAwareAspectJAutoProxyCreator的isInfrastructureClass()开始参与其它Bean的创建，并判断当前Bean是不是切面"></a>Debug调用栈-调用AnnotationAwareAspectJAutoProxyCreator的isInfrastructureClass()开始参与其它Bean的创建，并判断当前Bean是不是切面</h4><blockquote>
<p>从createBean里调用resolveBeforeInstantiation，AnnotationAwareAspectJAutoProxyCreator开始第一次发挥作用</p>
</blockquote>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">protected</span> Object <span class="title">createBean</span><span class="params">(String beanName, RootBeanDefinition mbd, <span class="meta">@Nullable</span> Object[] args)</span></span></span><br><span class="line"><span class="function">      <span class="keyword">throws</span> BeanCreationException </span>&#123;</span><br><span class="line"></span><br><span class="line">   <span class="keyword">if</span> (logger.isTraceEnabled()) &#123;</span><br><span class="line">      logger.trace(<span class="string">&quot;Creating instance of bean &#x27;&quot;</span> + beanName + <span class="string">&quot;&#x27;&quot;</span>);</span><br><span class="line">   &#125;</span><br><span class="line">   RootBeanDefinition mbdToUse = mbd;</span><br><span class="line"></span><br><span class="line">   Class&lt;?&gt; resolvedClass = resolveBeanClass(mbd, beanName);</span><br><span class="line">   <span class="keyword">if</span> (resolvedClass != <span class="keyword">null</span> &amp;&amp; !mbd.hasBeanClass() &amp;&amp; mbd.getBeanClassName() != <span class="keyword">null</span>) &#123;</span><br><span class="line">      mbdToUse = <span class="keyword">new</span> RootBeanDefinition(mbd);</span><br><span class="line">      mbdToUse.setBeanClass(resolvedClass);</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">   <span class="comment">// Prepare method overrides.</span></span><br><span class="line">   <span class="keyword">try</span> &#123;</span><br><span class="line">      mbdToUse.prepareMethodOverrides();</span><br><span class="line">   &#125;</span><br><span class="line">   <span class="keyword">catch</span> (BeanDefinitionValidationException ex) &#123;</span><br><span class="line">      <span class="keyword">throw</span> <span class="keyword">new</span> BeanDefinitionStoreException(mbdToUse.getResourceDescription(),</span><br><span class="line">            beanName, <span class="string">&quot;Validation of method overrides failed&quot;</span>, ex);</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">   <span class="keyword">try</span> &#123;</span><br><span class="line">      <span class="comment">//（即使AOP的BeanPostProcessor都不会珍惜这个机会） 提前给我们一个机会，去返回组件的代理对象。 Give BeanPostProcessors a chance to return a proxy instead of the target bean instance.</span></span><br><span class="line">      Object bean = resolveBeforeInstantiation(beanName, mbdToUse);</span><br><span class="line">      <span class="keyword">if</span> (bean != <span class="keyword">null</span>) &#123;</span><br><span class="line">         <span class="keyword">return</span> bean;</span><br><span class="line">      &#125;</span><br><span class="line">   &#125;</span><br><span class="line">   <span class="keyword">catch</span> (Throwable ex) &#123;</span><br><span class="line">      <span class="keyword">throw</span> <span class="keyword">new</span> BeanCreationException(mbdToUse.getResourceDescription(), beanName,</span><br><span class="line">            <span class="string">&quot;BeanPostProcessor before instantiation of bean failed&quot;</span>, ex);</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">   <span class="keyword">try</span> &#123; <span class="comment">//Spring真正自己创建对象</span></span><br><span class="line">      Object beanInstance = doCreateBean(beanName, mbdToUse, args);</span><br><span class="line">      <span class="keyword">if</span> (logger.isTraceEnabled()) &#123;</span><br><span class="line">         logger.trace(<span class="string">&quot;Finished creating instance of bean &#x27;&quot;</span> + beanName + <span class="string">&quot;&#x27;&quot;</span>);</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="keyword">return</span> beanInstance;</span><br><span class="line">   &#125;</span><br><span class="line">   <span class="keyword">catch</span> (BeanCreationException | ImplicitlyAppearedSingletonException ex) &#123;</span><br><span class="line">      <span class="keyword">throw</span> ex;</span><br><span class="line">   &#125;</span><br><span class="line">   <span class="keyword">catch</span> (Throwable ex) &#123;</span><br><span class="line">      <span class="keyword">throw</span> <span class="keyword">new</span> BeanCreationException(</span><br><span class="line">            mbdToUse.getResourceDescription(), beanName, <span class="string">&quot;Unexpected exception during bean creation&quot;</span>, ex);</span><br><span class="line">   &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_06/image-20211011224506258.png"/>

<ol>
<li>我们来看一下是什么时候触发的，看图中的beanName==myBeanPostProcessor时触发的，也就是创建完AnnotationAwareAspectJAutoProxyCreator，第一次创建别的后置处理器时触发的。</li>
<li>这里虽然开始参与其它Bean的创建过程，但也可能是什么都没做。</li>
<li>AnnotationAwareAspectJAutoProxyCreator的这个isInfrastructureClass()方法主要作用就是找到当前Bean的切面是哪些，存到一个Map里，后面可能会用到</li>
</ol>
<h5 id="AbstractAutowireCapableBeanFactory-resolveBeforeInstantiation"><a href="#AbstractAutowireCapableBeanFactory-resolveBeforeInstantiation" class="headerlink" title="AbstractAutowireCapableBeanFactory#resolveBeforeInstantiation()"></a>AbstractAutowireCapableBeanFactory#resolveBeforeInstantiation()</h5><figure class="highlight java"><table><tr><td class="code"><pre><span class="line">   <span class="meta">@Nullable</span></span><br><span class="line">   <span class="function"><span class="keyword">protected</span> Object <span class="title">resolveBeforeInstantiation</span><span class="params">(String beanName, RootBeanDefinition mbd)</span> </span>&#123;</span><br><span class="line">      Object bean = <span class="keyword">null</span>;</span><br><span class="line">      <span class="keyword">if</span> (!Boolean.FALSE.equals(mbd.beforeInstantiationResolved)) &#123;</span><br><span class="line">         <span class="comment">// Make sure bean class is actually resolved at this point.</span></span><br><span class="line">         <span class="keyword">if</span> (!mbd.isSynthetic() &amp;&amp; hasInstantiationAwareBeanPostProcessors()) &#123;</span><br><span class="line">            Class&lt;?&gt; targetType = determineTargetType(beanName, mbd);</span><br><span class="line">            <span class="keyword">if</span> (targetType != <span class="keyword">null</span>) &#123;</span><br><span class="line">               bean = applyBeanPostProcessorsBeforeInstantiation(targetType, beanName);</span><br><span class="line">               <span class="keyword">if</span> (bean != <span class="keyword">null</span>) &#123;</span><br><span class="line">                  bean = applyBeanPostProcessorsAfterInitialization(bean, beanName);</span><br><span class="line">               &#125;</span><br><span class="line">            &#125;</span><br><span class="line">         &#125;</span><br><span class="line">         mbd.beforeInstantiationResolved = (bean != <span class="keyword">null</span>);</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="keyword">return</span> bean;</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line"><span class="meta">@Nullable</span></span><br><span class="line"><span class="function"><span class="keyword">protected</span> Object <span class="title">applyBeanPostProcessorsBeforeInstantiation</span><span class="params">(Class&lt;?&gt; beanClass, String beanName)</span> </span>&#123;</span><br><span class="line">	<span class="keyword">for</span> (InstantiationAwareBeanPostProcessor bp : getBeanPostProcessorCache().instantiationAware) &#123;</span><br><span class="line">		Object result = bp.postProcessBeforeInstantiation(beanClass, beanName);</span><br><span class="line">		<span class="keyword">if</span> (result != <span class="keyword">null</span>) &#123;</span><br><span class="line">			<span class="keyword">return</span> result;</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h5 id="AbstractAutoProxyCreator-postProcessBeforeInstantiation"><a href="#AbstractAutoProxyCreator-postProcessBeforeInstantiation" class="headerlink" title="AbstractAutoProxyCreator#postProcessBeforeInstantiation()"></a>AbstractAutoProxyCreator#postProcessBeforeInstantiation()</h5><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="meta">@Override</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> Object <span class="title">postProcessBeforeInstantiation</span><span class="params">(Class&lt;?&gt; beanClass, String beanName)</span> </span>&#123;</span><br><span class="line">   Object cacheKey = getCacheKey(beanClass, beanName);</span><br><span class="line"></span><br><span class="line">   <span class="keyword">if</span> (!StringUtils.hasLength(beanName) || !<span class="keyword">this</span>.targetSourcedBeans.contains(beanName)) &#123;</span><br><span class="line">      <span class="keyword">if</span> (<span class="keyword">this</span>.advisedBeans.containsKey(cacheKey)) &#123; <span class="comment">//已经分析过的组件内</span></span><br><span class="line">         <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">      &#125; <span class="comment">//所有增强了的组件会被缓存在advisedBeans，如果我们需要增强的bean，我们就放在缓存中</span></span><br><span class="line">      <span class="keyword">if</span> (isInfrastructureClass(beanClass) || shouldSkip(beanClass, beanName)) &#123;</span><br><span class="line">         <span class="keyword">this</span>.advisedBeans.put(cacheKey, Boolean.FALSE);</span><br><span class="line">         <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">      &#125;</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">   <span class="comment">//创建个代理 Create proxy here if we have a custom TargetSource.</span></span><br><span class="line">   <span class="comment">// Suppresses unnecessary default instantiation of the target bean:</span></span><br><span class="line">   <span class="comment">// The TargetSource will handle target instances in a custom fashion.</span></span><br><span class="line">   TargetSource targetSource = getCustomTargetSource(beanClass, beanName);</span><br><span class="line">   <span class="keyword">if</span> (targetSource != <span class="keyword">null</span>) &#123;</span><br><span class="line">      <span class="keyword">if</span> (StringUtils.hasLength(beanName)) &#123;</span><br><span class="line">         <span class="keyword">this</span>.targetSourcedBeans.add(beanName);</span><br><span class="line">      &#125;</span><br><span class="line">      Object[] specificInterceptors = getAdvicesAndAdvisorsForBean(beanClass, beanName, targetSource);</span><br><span class="line">      Object proxy = createProxy(beanClass, beanName, specificInterceptors, targetSource);</span><br><span class="line">      <span class="keyword">this</span>.proxyTypes.put(cacheKey, proxy.getClass());</span><br><span class="line">      <span class="keyword">return</span> proxy;</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">   <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<blockquote>
<p>注意切面都已经存在了advisedBeans这个Map里</p>
</blockquote>
<h5 id="AnnotationAwareAspectJAutoProxyCreator-isInfrastructureClass-找哪些是切面"><a href="#AnnotationAwareAspectJAutoProxyCreator-isInfrastructureClass-找哪些是切面" class="headerlink" title="AnnotationAwareAspectJAutoProxyCreator#isInfrastructureClass()找哪些是切面"></a>AnnotationAwareAspectJAutoProxyCreator#isInfrastructureClass()找哪些是切面</h5><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">protected</span> <span class="keyword">boolean</span> <span class="title">isInfrastructureClass</span><span class="params">(Class&lt;?&gt; beanClass)</span> </span>&#123;</span><br><span class="line">   <span class="comment">// Previously we setProxyTargetClass(true) in the constructor, but that has too</span></span><br><span class="line">   <span class="comment">// broad an impact. Instead we now override isInfrastructureClass to avoid proxying</span></span><br><span class="line">   <span class="comment">// aspects. I&#x27;m not entirely happy with that as there is no good reason not</span></span><br><span class="line">   <span class="comment">// to advise aspects, except that it causes advice invocation to go through a</span></span><br><span class="line">   <span class="comment">// proxy, and if the aspect implements e.g the Ordered interface it will be</span></span><br><span class="line">   <span class="comment">// proxied by that interface and fail at runtime as the advice method is not</span></span><br><span class="line">   <span class="comment">// defined on the interface. We could potentially relax the restriction about</span></span><br><span class="line">   <span class="comment">// not advising aspects in the future.  判断是否切面</span></span><br><span class="line">   <span class="keyword">return</span> (<span class="keyword">super</span>.isInfrastructureClass(beanClass) ||</span><br><span class="line">         (<span class="keyword">this</span>.aspectJAdvisorFactory != <span class="keyword">null</span> &amp;&amp; <span class="keyword">this</span>.aspectJAdvisorFactory.isAspect(beanClass)));</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h5 id="AbstractAutoProxyCreator"><a href="#AbstractAutoProxyCreator" class="headerlink" title="AbstractAutoProxyCreator"></a>AbstractAutoProxyCreator</h5><figure class="highlight java"><table><tr><td class="code"><pre><span class="line">   <span class="comment">// 这个意思就是实现了Advice，Pointcut，Advisor，AopInfrastructureBean这些类也会把你当成是切面，不一定非要是注解</span></span><br><span class="line"><span class="function"><span class="keyword">protected</span> <span class="keyword">boolean</span> <span class="title">isInfrastructureClass</span><span class="params">(Class&lt;?&gt; beanClass)</span> </span>&#123;</span><br><span class="line">      <span class="keyword">boolean</span> retVal = Advice.class.isAssignableFrom(beanClass) ||</span><br><span class="line">            Pointcut.class.isAssignableFrom(beanClass) ||</span><br><span class="line">            Advisor.class.isAssignableFrom(beanClass) ||</span><br><span class="line">            AopInfrastructureBean.class.isAssignableFrom(beanClass);</span><br><span class="line">      <span class="keyword">if</span> (retVal &amp;&amp; logger.isTraceEnabled()) &#123;</span><br><span class="line">         logger.trace(<span class="string">&quot;Did not attempt to auto-proxy infrastructure class [&quot;</span> + beanClass.getName() + <span class="string">&quot;]&quot;</span>);</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="keyword">return</span> retVal;</span><br><span class="line">   &#125;</span><br></pre></td></tr></table></figure>

<h5 id="AbstractAspectJAdvisorFactory"><a href="#AbstractAspectJAdvisorFactory" class="headerlink" title="AbstractAspectJAdvisorFactory"></a>AbstractAspectJAdvisorFactory</h5><figure class="highlight java"><table><tr><td class="code"><pre><span class="line">   <span class="meta">@Override</span></span><br><span class="line">   <span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">isAspect</span><span class="params">(Class&lt;?&gt; clazz)</span> </span>&#123;</span><br><span class="line">      <span class="keyword">return</span> (hasAspectAnnotation(clazz) &amp;&amp; !compiledByAjc(clazz));</span><br><span class="line">   &#125;</span><br><span class="line"><span class="comment">//这里就是判断标注了@Aspect的才是切面</span></span><br><span class="line">   <span class="function"><span class="keyword">private</span> <span class="keyword">boolean</span> <span class="title">hasAspectAnnotation</span><span class="params">(Class&lt;?&gt; clazz)</span> </span>&#123;</span><br><span class="line">      <span class="keyword">return</span> (AnnotationUtils.findAnnotation(clazz, Aspect.class) != <span class="keyword">null</span>);</span><br><span class="line">   &#125;</span><br></pre></td></tr></table></figure>



<h4 id="Debug调用栈-调用aspectJAdvisorsBuilder的findCandidateAdvisors-方法"><a href="#Debug调用栈-调用aspectJAdvisorsBuilder的findCandidateAdvisors-方法" class="headerlink" title="Debug调用栈-调用aspectJAdvisorsBuilder的findCandidateAdvisors()方法"></a>Debug调用栈-调用aspectJAdvisorsBuilder的findCandidateAdvisors()方法</h4><img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_06/image-20211011230711617.png"/>

<p>AbstractAutoProxyCreator#postProcessBeforeInstantiation()这个方法，上面刚分析过，这次来分析shouldskip()</p>
<h5 id="AspectJAwareAdvisorAutoProxyCreator-shouldSkip"><a href="#AspectJAwareAdvisorAutoProxyCreator-shouldSkip" class="headerlink" title="AspectJAwareAdvisorAutoProxyCreator#shouldSkip()"></a>AspectJAwareAdvisorAutoProxyCreator#shouldSkip()</h5><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="meta">@Override</span>  <span class="comment">//判断是否需要跳过当前类</span></span><br><span class="line"><span class="function"><span class="keyword">protected</span> <span class="keyword">boolean</span> <span class="title">shouldSkip</span><span class="params">(Class&lt;?&gt; beanClass, String beanName)</span> </span>&#123;</span><br><span class="line">   <span class="comment">// <span class="doctag">TODO:</span> Consider optimization by caching the list of the aspect names</span></span><br><span class="line">   List&lt;Advisor&gt; candidateAdvisors = findCandidateAdvisors();  <span class="comment">//找到候选的增强器</span></span><br><span class="line">   <span class="keyword">for</span> (Advisor advisor : candidateAdvisors) &#123;</span><br><span class="line">      <span class="keyword">if</span> (advisor <span class="keyword">instanceof</span> AspectJPointcutAdvisor &amp;&amp;</span><br><span class="line">            ((AspectJPointcutAdvisor) advisor).getAspectName().equals(beanName)) &#123;</span><br><span class="line">         <span class="keyword">return</span> <span class="keyword">true</span>;</span><br><span class="line">      &#125;</span><br><span class="line">   &#125;</span><br><span class="line">   <span class="keyword">return</span> <span class="keyword">super</span>.shouldSkip(beanClass, beanName);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_06/image-20211011230223566.png"/>

<p>它进去的时候就是beanName==LogAspect，我们看看它是怎么判断的</p>
<h5 id="AnnotationAwareAspectJAutoProxyCreator-findCandidateAdvisors"><a href="#AnnotationAwareAspectJAutoProxyCreator-findCandidateAdvisors" class="headerlink" title="AnnotationAwareAspectJAutoProxyCreator#findCandidateAdvisors()"></a>AnnotationAwareAspectJAutoProxyCreator#findCandidateAdvisors()</h5><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="meta">@Override</span>  <span class="comment">//找到候选的增强器。</span></span><br><span class="line"><span class="function"><span class="keyword">protected</span> List&lt;Advisor&gt; <span class="title">findCandidateAdvisors</span><span class="params">()</span> </span>&#123;</span><br><span class="line">   <span class="comment">// Add all the Spring advisors found according to superclass rules. 判断这个bean是否需要增强只需要找到他的所有增强器</span></span><br><span class="line">   List&lt;Advisor&gt; advisors = <span class="keyword">super</span>.findCandidateAdvisors();</span><br><span class="line">   <span class="keyword">if</span> (<span class="keyword">this</span>.aspectJAdvisorsBuilder != <span class="keyword">null</span>) &#123; <span class="comment">//aspectJAdvisorsBuilder这个东西在上面创建aspectJAdvisorsBuilder就已经赋值了，所以这里不是null</span></span><br><span class="line">      advisors.addAll(<span class="keyword">this</span>.aspectJAdvisorsBuilder.buildAspectJAdvisors());</span><br><span class="line">   &#125;</span><br><span class="line">   <span class="keyword">return</span> advisors;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>我们这里先放行，看构造了哪些增强器</p>
<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_06/image-20211011233722352.png"/>

<h5 id="BeanFactoryAspectJAdvisorsBuilder-buildAspectJAdvisors-找到切面，并创建增强器advisors"><a href="#BeanFactoryAspectJAdvisorsBuilder-buildAspectJAdvisors-找到切面，并创建增强器advisors" class="headerlink" title="BeanFactoryAspectJAdvisorsBuilder#buildAspectJAdvisors()找到切面，并创建增强器advisors"></a>BeanFactoryAspectJAdvisorsBuilder#buildAspectJAdvisors()找到切面，并创建增强器advisors</h5><ol>
<li>可能会感觉到一点奇怪，此时beanName是myBeanPostProcessor，这个时候为什么要走到这里buildAspectJAdvisors（字面翻译就是构建增强器）这个方法。</li>
</ol>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> List&lt;Advisor&gt; <span class="title">buildAspectJAdvisors</span><span class="params">()</span> </span>&#123;</span><br><span class="line">   List&lt;String&gt; aspectNames = <span class="keyword">this</span>.aspectBeanNames; <span class="comment">//他是怎么知道切面名字的？</span></span><br><span class="line">   <span class="comment">//双检查锁的写法</span></span><br><span class="line">   <span class="keyword">if</span> (aspectNames == <span class="keyword">null</span>) &#123;</span><br><span class="line">      <span class="keyword">synchronized</span> (<span class="keyword">this</span>) &#123;</span><br><span class="line">         aspectNames = <span class="keyword">this</span>.aspectBeanNames;</span><br><span class="line">         <span class="keyword">if</span> (aspectNames == <span class="keyword">null</span>) &#123;</span><br><span class="line">            List&lt;Advisor&gt; advisors = <span class="keyword">new</span> ArrayList&lt;&gt;();</span><br><span class="line">            aspectNames = <span class="keyword">new</span> ArrayList&lt;&gt;();</span><br><span class="line">            <span class="comment">//获取容器中Object类型的组件，那意思就是获取所有组件</span></span><br><span class="line">            String[] beanNames = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(</span><br><span class="line">                  <span class="keyword">this</span>.beanFactory, Object.class, <span class="keyword">true</span>, <span class="keyword">false</span>);</span><br><span class="line">            <span class="comment">// for循环判断所有组件是不是切面，是的话就缓存</span></span><br><span class="line">            <span class="keyword">for</span> (String beanName : beanNames) &#123;</span><br><span class="line">               <span class="keyword">if</span> (!isEligibleBean(beanName)) &#123;</span><br><span class="line">                  <span class="keyword">continue</span>;</span><br><span class="line">               &#125;</span><br><span class="line">               <span class="comment">// We must be careful not to instantiate beans eagerly as in this case they</span></span><br><span class="line">               <span class="comment">// would be cached by the Spring container but would not have been weaved.</span></span><br><span class="line">               Class&lt;?&gt; beanType = <span class="keyword">this</span>.beanFactory.getType(beanName, <span class="keyword">false</span>);</span><br><span class="line">               <span class="keyword">if</span> (beanType == <span class="keyword">null</span>) &#123;</span><br><span class="line">                  <span class="keyword">continue</span>;</span><br><span class="line">               &#125;</span><br><span class="line">               <span class="comment">//</span></span><br><span class="line">               <span class="keyword">if</span> (<span class="keyword">this</span>.advisorFactory.isAspect(beanType)) &#123;</span><br><span class="line">                  aspectNames.add(beanName); <span class="comment">//每一个组件都先判断是否是切面，如果是放在集合中</span></span><br><span class="line">                  AspectMetadata amd = <span class="keyword">new</span> AspectMetadata(beanType, beanName);</span><br><span class="line">                  <span class="keyword">if</span> (amd.getAjType().getPerClause().getKind() == PerClauseKind.SINGLETON) &#123;</span><br><span class="line">                     MetadataAwareAspectInstanceFactory factory =</span><br><span class="line">                           <span class="keyword">new</span> BeanFactoryAspectInstanceFactory(<span class="keyword">this</span>.beanFactory, beanName);</span><br><span class="line">                     List&lt;Advisor&gt; classAdvisors = <span class="keyword">this</span>.advisorFactory.getAdvisors(factory); <span class="comment">//获取增强器</span></span><br><span class="line">                     <span class="keyword">if</span> (<span class="keyword">this</span>.beanFactory.isSingleton(beanName)) &#123;</span><br><span class="line">                        <span class="keyword">this</span>.advisorsCache.put(beanName, classAdvisors);</span><br><span class="line">                     &#125;</span><br><span class="line">                     <span class="keyword">else</span> &#123;</span><br><span class="line">                        <span class="keyword">this</span>.aspectFactoryCache.put(beanName, factory);</span><br><span class="line">                     &#125;</span><br><span class="line">                     advisors.addAll(classAdvisors);</span><br><span class="line">                  &#125;</span><br><span class="line">                  <span class="keyword">else</span> &#123;</span><br><span class="line">                     <span class="comment">// Per target or per this.</span></span><br><span class="line">                     <span class="keyword">if</span> (<span class="keyword">this</span>.beanFactory.isSingleton(beanName)) &#123;</span><br><span class="line">                        <span class="keyword">throw</span> <span class="keyword">new</span> IllegalArgumentException(<span class="string">&quot;Bean with name &#x27;&quot;</span> + beanName +</span><br><span class="line">                              <span class="string">&quot;&#x27; is a singleton, but aspect instantiation model is not singleton&quot;</span>);</span><br><span class="line">                     &#125;</span><br><span class="line">                     MetadataAwareAspectInstanceFactory factory =</span><br><span class="line">                           <span class="keyword">new</span> PrototypeAspectInstanceFactory(<span class="keyword">this</span>.beanFactory, beanName);</span><br><span class="line">                     <span class="keyword">this</span>.aspectFactoryCache.put(beanName, factory);</span><br><span class="line">                     advisors.addAll(<span class="keyword">this</span>.advisorFactory.getAdvisors(factory));</span><br><span class="line">                  &#125;</span><br><span class="line">               &#125;</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">this</span>.aspectBeanNames = aspectNames;</span><br><span class="line">            <span class="keyword">return</span> advisors;</span><br><span class="line">         &#125;</span><br><span class="line">      &#125;</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">   <span class="keyword">if</span> (aspectNames.isEmpty()) &#123;</span><br><span class="line">      <span class="keyword">return</span> Collections.emptyList();</span><br><span class="line">   &#125;</span><br><span class="line">   List&lt;Advisor&gt; advisors = <span class="keyword">new</span> ArrayList&lt;&gt;(); <span class="comment">//</span></span><br><span class="line">   <span class="keyword">for</span> (String aspectName : aspectNames) &#123; <span class="comment">//遍历所有的切面找增强器</span></span><br><span class="line">      List&lt;Advisor&gt; cachedAdvisors = <span class="keyword">this</span>.advisorsCache.get(aspectName);</span><br><span class="line">      <span class="keyword">if</span> (cachedAdvisors != <span class="keyword">null</span>) &#123;</span><br><span class="line">         advisors.addAll(cachedAdvisors);</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="keyword">else</span> &#123;</span><br><span class="line">         MetadataAwareAspectInstanceFactory factory = <span class="keyword">this</span>.aspectFactoryCache.get(aspectName);</span><br><span class="line">         advisors.addAll(<span class="keyword">this</span>.advisorFactory.getAdvisors(factory));</span><br><span class="line">      &#125;</span><br><span class="line">   &#125;</span><br><span class="line">   <span class="keyword">return</span> advisors;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_06/image-20211011232136364.png"/>

<p>for循环所有组件之后，有切面的话，就赋值，然后aspectNames</p>
<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_06/image-20211011232645429.png"/>

<h4 id="结论"><a href="#结论" class="headerlink" title="结论"></a>结论</h4><ol>
<li>最终在BeanName是myBeanPostProcessor的时候，或者说在我们创建完AnnotationAwareAspectJAutoProxyCreator这个后置处理器之后，再接着创建下一个组件的时候。createBean()里调用resolveBeforeInstantiation()，AnnotationAwareAspectJAutoProxyCreator后置处理器开始第一次发挥作用，提前就把切面的名字找到了logAspect，并且找到了这个logAspect切面的4个增强器。</li>
<li>具体构建增强器的过程下面马上会讲，讲之前再看一个问题</li>
</ol>
<h4 id="isInfrastructureClass-和shouldSkip-区别"><a href="#isInfrastructureClass-和shouldSkip-区别" class="headerlink" title="isInfrastructureClass()和shouldSkip()区别"></a>isInfrastructureClass()和shouldSkip()区别</h4><p>AbstractAutoProxyCreator</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="meta">@Override</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> Object <span class="title">postProcessBeforeInstantiation</span><span class="params">(Class&lt;?&gt; beanClass, String beanName)</span> </span>&#123;</span><br><span class="line">   Object cacheKey = getCacheKey(beanClass, beanName);</span><br><span class="line"></span><br><span class="line">   <span class="keyword">if</span> (!StringUtils.hasLength(beanName) || !<span class="keyword">this</span>.targetSourcedBeans.contains(beanName)) &#123;</span><br><span class="line">      <span class="keyword">if</span> (<span class="keyword">this</span>.advisedBeans.containsKey(cacheKey)) &#123; <span class="comment">//已经分析过的组件内</span></span><br><span class="line">         <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">      &#125; <span class="comment">//所有增强了的组件会被缓存在advisedBeans，如果我们需要增强的bean，我们就放在缓存中</span></span><br><span class="line">      <span class="keyword">if</span> (isInfrastructureClass(beanClass) || shouldSkip(beanClass, beanName)) &#123;</span><br><span class="line">         <span class="keyword">this</span>.advisedBeans.put(cacheKey, Boolean.FALSE);</span><br><span class="line">         <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">      &#125;</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">   <span class="comment">//创建个代理 Create proxy here if we have a custom TargetSource.</span></span><br><span class="line">   <span class="comment">// Suppresses unnecessary default instantiation of the target bean:</span></span><br><span class="line">   <span class="comment">// The TargetSource will handle target instances in a custom fashion.</span></span><br><span class="line">   TargetSource targetSource = getCustomTargetSource(beanClass, beanName);</span><br><span class="line">   <span class="keyword">if</span> (targetSource != <span class="keyword">null</span>) &#123;</span><br><span class="line">      <span class="keyword">if</span> (StringUtils.hasLength(beanName)) &#123;</span><br><span class="line">         <span class="keyword">this</span>.targetSourcedBeans.add(beanName);</span><br><span class="line">      &#125;</span><br><span class="line">      Object[] specificInterceptors = getAdvicesAndAdvisorsForBean(beanClass, beanName, targetSource);</span><br><span class="line">      Object proxy = createProxy(beanClass, beanName, specificInterceptors, targetSource);</span><br><span class="line">      <span class="keyword">this</span>.proxyTypes.put(cacheKey, proxy.getClass());</span><br><span class="line">      <span class="keyword">return</span> proxy;</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">   <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<ol>
<li>在前面讲isInfrastructureClass()的时候，我们发现它会找当前Bean的切面，并判断当前Bean是不是切面。如果当前Bean是切面，那么就不会走shouldSkip，直接放到advisedBeans这个Map里。比如当这里的beanName是logAspect的时候，就直接放到advisedBeans里。</li>
<li>放到advisedBeans的作用就是后面在进行代理的时候，会跳过logAspect本身。</li>
<li>如果当前bean不是切面，才会走shouldSkip，不过shouldSkip里for循环分析的是所有的bean，找哪些是切面</li>
</ol>
<h3 id="构建增强器的过程"><a href="#构建增强器的过程" class="headerlink" title="构建增强器的过程"></a>构建增强器的过程</h3><p>我们再来看下构建增强器的具体过程</p>
<h4 id="BeanactoryAspectJAdvisorsBuilder-buildAspectJAdvisors真正开始构建增强器"><a href="#BeanactoryAspectJAdvisorsBuilder-buildAspectJAdvisors真正开始构建增强器" class="headerlink" title="BeanactoryAspectJAdvisorsBuilder#buildAspectJAdvisors真正开始构建增强器"></a>BeanactoryAspectJAdvisorsBuilder#buildAspectJAdvisors真正开始构建增强器</h4><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> List&lt;Advisor&gt; <span class="title">buildAspectJAdvisors</span><span class="params">()</span> </span>&#123;</span><br><span class="line">   List&lt;String&gt; aspectNames = <span class="keyword">this</span>.aspectBeanNames; <span class="comment">//他是怎么知道切面名字的</span></span><br><span class="line">   <span class="comment">//双检查锁的写法</span></span><br><span class="line">   <span class="keyword">if</span> (aspectNames == <span class="keyword">null</span>) &#123;</span><br><span class="line">      <span class="keyword">synchronized</span> (<span class="keyword">this</span>) &#123;</span><br><span class="line">         aspectNames = <span class="keyword">this</span>.aspectBeanNames;</span><br><span class="line">         <span class="keyword">if</span> (aspectNames == <span class="keyword">null</span>) &#123;</span><br><span class="line">            List&lt;Advisor&gt; advisors = <span class="keyword">new</span> ArrayList&lt;&gt;();</span><br><span class="line">            aspectNames = <span class="keyword">new</span> ArrayList&lt;&gt;();</span><br><span class="line">            String[] beanNames = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(</span><br><span class="line">                  <span class="keyword">this</span>.beanFactory, Object.class, <span class="keyword">true</span>, <span class="keyword">false</span>);</span><br><span class="line">            <span class="keyword">for</span> (String beanName : beanNames) &#123;</span><br><span class="line">               <span class="keyword">if</span> (!isEligibleBean(beanName)) &#123;</span><br><span class="line">                  <span class="keyword">continue</span>;</span><br><span class="line">               &#125;</span><br><span class="line">               <span class="comment">// We must be careful not to instantiate beans eagerly as in this case they</span></span><br><span class="line">               <span class="comment">// would be cached by the Spring container but would not have been weaved.</span></span><br><span class="line">               Class&lt;?&gt; beanType = <span class="keyword">this</span>.beanFactory.getType(beanName, <span class="keyword">false</span>);</span><br><span class="line">               <span class="keyword">if</span> (beanType == <span class="keyword">null</span>) &#123;</span><br><span class="line">                  <span class="keyword">continue</span>;</span><br><span class="line">               &#125;</span><br><span class="line">                <span class="comment">//这里也判断了一次，循环的beanName是否是切面</span></span><br><span class="line">               <span class="keyword">if</span> (<span class="keyword">this</span>.advisorFactory.isAspect(beanType)) &#123;</span><br><span class="line">                  aspectNames.add(beanName); <span class="comment">//每一个组件都先判断是否是切面，如果是放在集合中</span></span><br><span class="line">                  AspectMetadata amd = <span class="keyword">new</span> AspectMetadata(beanType, beanName);</span><br><span class="line">                  <span class="keyword">if</span> (amd.getAjType().getPerClause().getKind() == PerClauseKind.SINGLETON) &#123;</span><br><span class="line">                     MetadataAwareAspectInstanceFactory factory =</span><br><span class="line">                           <span class="keyword">new</span> BeanFactoryAspectInstanceFactory(<span class="keyword">this</span>.beanFactory, beanName);</span><br><span class="line">                     List&lt;Advisor&gt; classAdvisors = <span class="keyword">this</span>.advisorFactory.getAdvisors(factory); <span class="comment">//获取增强器</span></span><br><span class="line">                     <span class="keyword">if</span> (<span class="keyword">this</span>.beanFactory.isSingleton(beanName)) &#123;</span><br><span class="line">                        <span class="keyword">this</span>.advisorsCache.put(beanName, classAdvisors);</span><br><span class="line">                     &#125;</span><br><span class="line">                     <span class="keyword">else</span> &#123;</span><br><span class="line">                        <span class="keyword">this</span>.aspectFactoryCache.put(beanName, factory);</span><br><span class="line">                     &#125;</span><br><span class="line">                     advisors.addAll(classAdvisors);</span><br><span class="line">                  &#125;</span><br><span class="line">                  <span class="keyword">else</span> &#123;</span><br><span class="line">                     <span class="comment">// Per target or per this.</span></span><br><span class="line">                     <span class="keyword">if</span> (<span class="keyword">this</span>.beanFactory.isSingleton(beanName)) &#123;</span><br><span class="line">                        <span class="keyword">throw</span> <span class="keyword">new</span> IllegalArgumentException(<span class="string">&quot;Bean with name &#x27;&quot;</span> + beanName +</span><br><span class="line">                              <span class="string">&quot;&#x27; is a singleton, but aspect instantiation model is not singleton&quot;</span>);</span><br><span class="line">                     &#125;</span><br><span class="line">                     MetadataAwareAspectInstanceFactory factory =</span><br><span class="line">                           <span class="keyword">new</span> PrototypeAspectInstanceFactory(<span class="keyword">this</span>.beanFactory, beanName);</span><br><span class="line">                     <span class="keyword">this</span>.aspectFactoryCache.put(beanName, factory);</span><br><span class="line">                     advisors.addAll(<span class="keyword">this</span>.advisorFactory.getAdvisors(factory));</span><br><span class="line">                  &#125;</span><br><span class="line">               &#125;</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">this</span>.aspectBeanNames = aspectNames;</span><br><span class="line">            <span class="keyword">return</span> advisors;</span><br><span class="line">         &#125;</span><br><span class="line">      &#125;</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">   <span class="keyword">if</span> (aspectNames.isEmpty()) &#123;</span><br><span class="line">      <span class="keyword">return</span> Collections.emptyList();</span><br><span class="line">   &#125;</span><br><span class="line">   List&lt;Advisor&gt; advisors = <span class="keyword">new</span> ArrayList&lt;&gt;(); <span class="comment">//</span></span><br><span class="line">   <span class="keyword">for</span> (String aspectName : aspectNames) &#123; <span class="comment">//遍历所有的切面找增强器</span></span><br><span class="line">      List&lt;Advisor&gt; cachedAdvisors = <span class="keyword">this</span>.advisorsCache.get(aspectName);</span><br><span class="line">      <span class="keyword">if</span> (cachedAdvisors != <span class="keyword">null</span>) &#123;</span><br><span class="line">         advisors.addAll(cachedAdvisors);</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="keyword">else</span> &#123;</span><br><span class="line">         MetadataAwareAspectInstanceFactory factory = <span class="keyword">this</span>.aspectFactoryCache.get(aspectName);</span><br><span class="line">         advisors.addAll(<span class="keyword">this</span>.advisorFactory.getAdvisors(factory));</span><br><span class="line">      &#125;</span><br><span class="line">   &#125;</span><br><span class="line">   <span class="keyword">return</span> advisors;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h4 id="ReflectiveAspectJAdvisorFactory-getAdvisors-找到切面里面定义的所有增强器"><a href="#ReflectiveAspectJAdvisorFactory-getAdvisors-找到切面里面定义的所有增强器" class="headerlink" title="ReflectiveAspectJAdvisorFactory#getAdvisors()找到切面里面定义的所有增强器"></a>ReflectiveAspectJAdvisorFactory#getAdvisors()找到切面里面定义的所有增强器</h4><p>增强器就是@before,@after这些标注的</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line">   <span class="meta">@Override</span> <span class="comment">//找到切面里面定义的所有增强器</span></span><br><span class="line">   <span class="function"><span class="keyword">public</span> List&lt;Advisor&gt; <span class="title">getAdvisors</span><span class="params">(MetadataAwareAspectInstanceFactory aspectInstanceFactory)</span> </span>&#123;</span><br><span class="line">      Class&lt;?&gt; aspectClass = aspectInstanceFactory.getAspectMetadata().getAspectClass();</span><br><span class="line">      String aspectName = aspectInstanceFactory.getAspectMetadata().getAspectName();</span><br><span class="line">      validate(aspectClass);</span><br><span class="line"></span><br><span class="line">      <span class="comment">// We need to wrap the MetadataAwareAspectInstanceFactory with a decorator</span></span><br><span class="line">      <span class="comment">// so that it will only instantiate once.</span></span><br><span class="line">      MetadataAwareAspectInstanceFactory lazySingletonAspectInstanceFactory =</span><br><span class="line">            <span class="keyword">new</span> LazySingletonAspectInstanceFactoryDecorator(aspectInstanceFactory);</span><br><span class="line"></span><br><span class="line">      List&lt;Advisor&gt; advisors = <span class="keyword">new</span> ArrayList&lt;&gt;(); <span class="comment">//收集所有增强器</span></span><br><span class="line">       <span class="comment">// 从切面类获取增强方法</span></span><br><span class="line">      <span class="keyword">for</span> (Method method : getAdvisorMethods(aspectClass)) &#123;</span><br><span class="line">         <span class="comment">// Prior to Spring Framework 5.2.7, advisors.size() was supplied as the declarationOrderInAspect</span></span><br><span class="line">         <span class="comment">// to getAdvisor(...) to represent the &quot;current position&quot; in the declared methods list.</span></span><br><span class="line">         <span class="comment">// However, since Java 7 the &quot;current position&quot; is not valid since the JDK no longer</span></span><br><span class="line">         <span class="comment">// returns declared methods in the order in which they are declared in the source code.</span></span><br><span class="line">         <span class="comment">// Thus, we now hard code the declarationOrderInAspect to 0 for all advice methods</span></span><br><span class="line">         <span class="comment">// discovered via reflection in order to support reliable advice ordering across JVM launches.</span></span><br><span class="line">         <span class="comment">// Specifically, a value of 0 aligns with the default value used in</span></span><br><span class="line">         <span class="comment">// AspectJPrecedenceComparator.getAspectDeclarationOrder(Advisor). //分析如果当前方法是通知方法则封装为Advisor</span></span><br><span class="line">         Advisor advisor = getAdvisor(method, lazySingletonAspectInstanceFactory, <span class="number">0</span>, aspectName);</span><br><span class="line">         <span class="keyword">if</span> (advisor != <span class="keyword">null</span>) &#123;</span><br><span class="line">            advisors.add(advisor);</span><br><span class="line">         &#125;</span><br><span class="line">      &#125;</span><br><span class="line"></span><br><span class="line">      <span class="comment">// If it&#x27;s a per target aspect, emit the dummy instantiating aspect.</span></span><br><span class="line">      <span class="keyword">if</span> (!advisors.isEmpty() &amp;&amp; lazySingletonAspectInstanceFactory.getAspectMetadata().isLazilyInstantiated()) &#123;</span><br><span class="line">         Advisor instantiationAdvisor = <span class="keyword">new</span> SyntheticInstantiationAdvisor(lazySingletonAspectInstanceFactory);</span><br><span class="line">         advisors.add(<span class="number">0</span>, instantiationAdvisor);</span><br><span class="line">      &#125;</span><br><span class="line"></span><br><span class="line">      <span class="comment">// 需要增强的属性： 主要针对@DeclareParents ； Find introduction fields.</span></span><br><span class="line">      <span class="keyword">for</span> (Field field : aspectClass.getDeclaredFields()) &#123;</span><br><span class="line">         Advisor advisor = getDeclareParentsAdvisor(field);</span><br><span class="line">         <span class="keyword">if</span> (advisor != <span class="keyword">null</span>) &#123;</span><br><span class="line">            advisors.add(advisor);</span><br><span class="line">         &#125;</span><br><span class="line">      &#125;</span><br><span class="line"></span><br><span class="line">      <span class="keyword">return</span> advisors;</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">private</span> List&lt;Method&gt; <span class="title">getAdvisorMethods</span><span class="params">(Class&lt;?&gt; aspectClass)</span> </span>&#123;</span><br><span class="line">	List&lt;Method&gt; methods = <span class="keyword">new</span> ArrayList&lt;&gt;(); <span class="comment">//methods.add(method)</span></span><br><span class="line">	ReflectionUtils.doWithMethods(aspectClass, methods::add, adviceMethodFilter);</span><br><span class="line">	<span class="keyword">if</span> (methods.size() &gt; <span class="number">1</span>) &#123;</span><br><span class="line">		methods.sort(adviceMethodComparator);</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">return</span> methods;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>



<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_06/image-20211012113939403.png"/>





<h4 id="ReflectionUtils"><a href="#ReflectionUtils" class="headerlink" title="ReflectionUtils"></a>ReflectionUtils</h4><figure class="highlight java"><table><tr><td class="code"><pre><span class="line">   <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">doWithMethods</span><span class="params">(Class&lt;?&gt; clazz, MethodCallback mc, <span class="meta">@Nullable</span> MethodFilter mf)</span> </span>&#123;</span><br><span class="line">       <span class="comment">// Keep backing up the inheritance hierarchy. 获取所有方法</span></span><br><span class="line">       Method[] methods = getDeclaredMethods(clazz, <span class="keyword">false</span>);</span><br><span class="line">       <span class="comment">// 下面的for循环只是收集clazz里的所有方法，不做任何过滤</span></span><br><span class="line">       <span class="keyword">for</span> (Method method : methods) &#123;</span><br><span class="line">           <span class="keyword">if</span> (mf != <span class="keyword">null</span> &amp;&amp; !mf.matches(method)) &#123;</span><br><span class="line">               <span class="keyword">continue</span>;</span><br><span class="line">           &#125;</span><br><span class="line">           <span class="keyword">try</span> &#123;</span><br><span class="line">                 <span class="comment">// 这里就是回调上面的methods::add，也就是list的add方法，给methods里面添加东西</span></span><br><span class="line">               mc.doWith(method);</span><br><span class="line">           &#125;</span><br><span class="line">           <span class="keyword">catch</span> (IllegalAccessException ex) &#123;</span><br><span class="line">               <span class="keyword">throw</span> <span class="keyword">new</span> IllegalStateException(<span class="string">&quot;Not allowed to access method &#x27;&quot;</span> + method.getName() + <span class="string">&quot;&#x27;: &quot;</span> + ex);</span><br><span class="line">           &#125;</span><br><span class="line">       &#125;</span><br><span class="line">       <span class="comment">//</span></span><br><span class="line">       <span class="keyword">if</span> (clazz.getSuperclass() != <span class="keyword">null</span> &amp;&amp; (mf != USER_DECLARED_METHODS || clazz.getSuperclass() != Object.class)) &#123;</span><br><span class="line">           <span class="comment">// 这里就是继续调用此方法获取父类的方法</span></span><br><span class="line">           doWithMethods(clazz.getSuperclass(), mc, mf);</span><br><span class="line">       &#125;</span><br><span class="line">       <span class="keyword">else</span> <span class="keyword">if</span> (clazz.isInterface()) &#123;</span><br><span class="line">           <span class="keyword">for</span> (Class&lt;?&gt; superIfc : clazz.getInterfaces()) &#123;</span><br><span class="line">               doWithMethods(superIfc, mc, mf);</span><br><span class="line">           &#125;</span><br><span class="line">       &#125;</span><br><span class="line">   &#125;</span><br><span class="line"><span class="comment">// 这应该是判断是不是桥接方法，合成方法什么的。具体我也不太懂</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">final</span> MethodFilter USER_DECLARED_METHODS = (method -&gt; !method.isBridge() &amp;&amp; !method.isSynthetic());</span><br></pre></td></tr></table></figure>



<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_06/image-20211012115005897.png"/>



<p>获取父类的方法</p>
<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_06/image-20211012115205531.png"/>

<p>然后回到这里</p>
<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_06/image-20211012142115626.png"/>

<p>最后回到这个for循环，循环所有的方法</p>
<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_06/image-20211012142802483.png"/>

<h4 id="ReflectiveAspectJAdvisorFactory-getAdvisor"><a href="#ReflectiveAspectJAdvisorFactory-getAdvisor" class="headerlink" title="ReflectiveAspectJAdvisorFactory#getAdvisor()"></a>ReflectiveAspectJAdvisorFactory#getAdvisor()</h4><figure class="highlight java"><table><tr><td class="code"><pre><span class="line">   <span class="function"><span class="keyword">public</span> Advisor <span class="title">getAdvisor</span><span class="params">(Method candidateAdviceMethod, MetadataAwareAspectInstanceFactory aspectInstanceFactory,</span></span></span><br><span class="line"><span class="function"><span class="params">         <span class="keyword">int</span> declarationOrderInAspect, String aspectName)</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">      validate(aspectInstanceFactory.getAspectMetadata().getAspectClass());</span><br><span class="line"></span><br><span class="line">      AspectJExpressionPointcut expressionPointcut = getPointcut(</span><br><span class="line">            candidateAdviceMethod, aspectInstanceFactory.getAspectMetadata().getAspectClass());</span><br><span class="line">      <span class="keyword">if</span> (expressionPointcut == <span class="keyword">null</span>) &#123;</span><br><span class="line">         <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">      &#125;</span><br><span class="line">  </span><br><span class="line">      <span class="comment">// 将信息都封装成Advisor实现类</span></span><br><span class="line">      <span class="keyword">return</span> <span class="keyword">new</span> InstantiationModelAwarePointcutAdvisorImpl(expressionPointcut, candidateAdviceMethod,</span><br><span class="line">            <span class="keyword">this</span>, aspectInstanceFactory, declarationOrderInAspect, aspectName);</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">private</span> AspectJExpressionPointcut <span class="title">getPointcut</span><span class="params">(Method candidateAdviceMethod, Class&lt;?&gt; candidateAspectClass)</span> </span>&#123;</span><br><span class="line">       <span class="comment">// 解析注解</span></span><br><span class="line">	AspectJAnnotation&lt;?&gt; aspectJAnnotation =</span><br><span class="line">			AbstractAspectJAdvisorFactory.findAspectJAnnotationOnMethod(candidateAdviceMethod);</span><br><span class="line">	<span class="keyword">if</span> (aspectJAnnotation == <span class="keyword">null</span>) &#123;</span><br><span class="line">		<span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	AspectJExpressionPointcut ajexp =</span><br><span class="line">			<span class="keyword">new</span> AspectJExpressionPointcut(candidateAspectClass, <span class="keyword">new</span> String[<span class="number">0</span>], <span class="keyword">new</span> Class&lt;?&gt;[<span class="number">0</span>]);</span><br><span class="line">	ajexp.setExpression(aspectJAnnotation.getPointcutExpression());</span><br><span class="line">	<span class="keyword">if</span> (<span class="keyword">this</span>.beanFactory != <span class="keyword">null</span>) &#123;</span><br><span class="line">		ajexp.setBeanFactory(<span class="keyword">this</span>.beanFactory);</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">return</span> ajexp;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h4 id="AbstractAspectJAdvisorFactory-1"><a href="#AbstractAspectJAdvisorFactory-1" class="headerlink" title="AbstractAspectJAdvisorFactory"></a>AbstractAspectJAdvisorFactory</h4><figure class="highlight java"><table><tr><td class="code"><pre><span class="line">   <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> Class&lt;?&gt;[] ASPECTJ_ANNOTATION_CLASSES = <span class="keyword">new</span> Class&lt;?&gt;[] &#123;</span><br><span class="line">		Pointcut.class, Around.class, Before.class, After.class, AfterReturning.class, AfterThrowing.class&#125;;</span><br><span class="line"></span><br><span class="line"><span class="meta">@Nullable</span></span><br><span class="line">   <span class="keyword">protected</span> <span class="keyword">static</span> AspectJAnnotation&lt;?&gt; findAspectJAnnotationOnMethod(Method method) &#123;</span><br><span class="line">      <span class="keyword">for</span> (Class&lt;?&gt; clazz : ASPECTJ_ANNOTATION_CLASSES) &#123;</span><br><span class="line">         AspectJAnnotation&lt;?&gt; foundAnnotation = findAnnotation(method, (Class&lt;Annotation&gt;) clazz);</span><br><span class="line">         <span class="keyword">if</span> (foundAnnotation != <span class="keyword">null</span>) &#123;</span><br><span class="line">            <span class="keyword">return</span> foundAnnotation;</span><br><span class="line">         &#125;</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">   &#125;</span><br></pre></td></tr></table></figure>

<p>可以看到就是解析了注解</p>
<h3 id="createBean-里调用doCreateBean-，AnnotationAwareAspectJAutoProxyCreator开始第二次发挥作用"><a href="#createBean-里调用doCreateBean-，AnnotationAwareAspectJAutoProxyCreator开始第二次发挥作用" class="headerlink" title="createBean()里调用doCreateBean()，AnnotationAwareAspectJAutoProxyCreator开始第二次发挥作用"></a>createBean()里调用doCreateBean()，AnnotationAwareAspectJAutoProxyCreator开始第二次发挥作用</h3><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">protected</span> Object <span class="title">createBean</span><span class="params">(String beanName, RootBeanDefinition mbd, <span class="meta">@Nullable</span> Object[] args)</span></span></span><br><span class="line"><span class="function">      <span class="keyword">throws</span> BeanCreationException </span>&#123;</span><br><span class="line"></span><br><span class="line">   <span class="keyword">if</span> (logger.isTraceEnabled()) &#123;</span><br><span class="line">      logger.trace(<span class="string">&quot;Creating instance of bean &#x27;&quot;</span> + beanName + <span class="string">&quot;&#x27;&quot;</span>);</span><br><span class="line">   &#125;</span><br><span class="line">   RootBeanDefinition mbdToUse = mbd;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">   Class&lt;?&gt; resolvedClass = resolveBeanClass(mbd, beanName);</span><br><span class="line">   <span class="keyword">if</span> (resolvedClass != <span class="keyword">null</span> &amp;&amp; !mbd.hasBeanClass() &amp;&amp; mbd.getBeanClassName() != <span class="keyword">null</span>) &#123;</span><br><span class="line">      mbdToUse = <span class="keyword">new</span> RootBeanDefinition(mbd);</span><br><span class="line">      mbdToUse.setBeanClass(resolvedClass);</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">   <span class="comment">// Prepare method overrides.</span></span><br><span class="line">   <span class="keyword">try</span> &#123;</span><br><span class="line">      mbdToUse.prepareMethodOverrides();</span><br><span class="line">   &#125;</span><br><span class="line">   <span class="keyword">catch</span> (BeanDefinitionValidationException ex) &#123;</span><br><span class="line">      <span class="keyword">throw</span> <span class="keyword">new</span> BeanDefinitionStoreException(mbdToUse.getResourceDescription(),</span><br><span class="line">            beanName, <span class="string">&quot;Validation of method overrides failed&quot;</span>, ex);</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">   <span class="keyword">try</span> &#123;</span><br><span class="line">      <span class="comment">//（即使AOP的BeanPostProcessor都不会珍惜这个机会） 提前给我们一个机会，去返回组件的代理对象。 Give BeanPostProcessors a chance to return a proxy instead of the target bean instance.</span></span><br><span class="line">      Object bean = resolveBeforeInstantiation(beanName, mbdToUse);</span><br><span class="line">      <span class="keyword">if</span> (bean != <span class="keyword">null</span>) &#123;</span><br><span class="line">         <span class="keyword">return</span> bean;</span><br><span class="line">      &#125;</span><br><span class="line">   &#125;</span><br><span class="line">   <span class="keyword">catch</span> (Throwable ex) &#123;</span><br><span class="line">      <span class="keyword">throw</span> <span class="keyword">new</span> BeanCreationException(mbdToUse.getResourceDescription(), beanName,</span><br><span class="line">            <span class="string">&quot;BeanPostProcessor before instantiation of bean failed&quot;</span>, ex);</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">   <span class="keyword">try</span> &#123; <span class="comment">//Spring真正自己创建对象</span></span><br><span class="line">      Object beanInstance = doCreateBean(beanName, mbdToUse, args);</span><br><span class="line">      <span class="keyword">if</span> (logger.isTraceEnabled()) &#123;</span><br><span class="line">         logger.trace(<span class="string">&quot;Finished creating instance of bean &#x27;&quot;</span> + beanName + <span class="string">&quot;&#x27;&quot;</span>);</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="keyword">return</span> beanInstance;</span><br><span class="line">   &#125;</span><br><span class="line">   <span class="keyword">catch</span> (BeanCreationException | ImplicitlyAppearedSingletonException ex) &#123;</span><br><span class="line"></span><br><span class="line">      <span class="keyword">throw</span> ex;</span><br><span class="line">   &#125;</span><br><span class="line">   <span class="keyword">catch</span> (Throwable ex) &#123;</span><br><span class="line">      <span class="keyword">throw</span> <span class="keyword">new</span> BeanCreationException(</span><br><span class="line">            mbdToUse.getResourceDescription(), beanName, <span class="string">&quot;Unexpected exception during bean creation&quot;</span>, ex);</span><br><span class="line">   &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h4 id="Debug调用栈-1"><a href="#Debug调用栈-1" class="headerlink" title="Debug调用栈"></a>Debug调用栈</h4><p>继续放行debug</p>
<p>到了初始化这里了，说明前面无参构造创建myBeanPostProcessor对象已经完成了</p>
<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_06/image-20211011233400056.png"/>

<h4 id="AnnotationAwareAspectJAutoProxyCreator-findCandidateAdvisors-1"><a href="#AnnotationAwareAspectJAutoProxyCreator-findCandidateAdvisors-1" class="headerlink" title="AnnotationAwareAspectJAutoProxyCreator#findCandidateAdvisors()"></a>AnnotationAwareAspectJAutoProxyCreator#findCandidateAdvisors()</h4><p>又来到了这个方法</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">protected</span> List&lt;Advisor&gt; <span class="title">findCandidateAdvisors</span><span class="params">()</span> </span>&#123;</span><br><span class="line">   <span class="comment">// Add all the Spring advisors found according to superclass rules. 判断这个bean是否需要增强只需要找到他的所有增强器</span></span><br><span class="line">   List&lt;Advisor&gt; advisors = <span class="keyword">super</span>.findCandidateAdvisors();</span><br><span class="line">   <span class="comment">// 我不需要增强，难道还要给我构建增强器？？？？ Build Advisors for all AspectJ aspects in the bean factory.</span></span><br><span class="line">   <span class="keyword">if</span> (<span class="keyword">this</span>.aspectJAdvisorsBuilder != <span class="keyword">null</span>) &#123; <span class="comment">//增强器的构建器只要有</span></span><br><span class="line">      advisors.addAll(<span class="keyword">this</span>.aspectJAdvisorsBuilder.buildAspectJAdvisors());</span><br><span class="line">   &#125;</span><br><span class="line">   <span class="keyword">return</span> advisors;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<p>我们这里先放行，看构造了哪些增强器</p>
<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_06/image-20211011233722352.png"/>

<h4 id="BeanFactoryAspectJAdvisorsBuilder-buildAspectJAdvisors"><a href="#BeanFactoryAspectJAdvisorsBuilder-buildAspectJAdvisors" class="headerlink" title="BeanFactoryAspectJAdvisorsBuilder#buildAspectJAdvisors()"></a>BeanFactoryAspectJAdvisorsBuilder#buildAspectJAdvisors()</h4><p>在这个resolveBeforeInstantiation()方法里，我们已经把aspectNames找到了，aspectNames!=null，就不走第一个if了</p>
<p>然后又再次来到了这个方法，开始在这里构造增强器了</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> List&lt;Advisor&gt; <span class="title">buildAspectJAdvisors</span><span class="params">()</span> </span>&#123;</span><br><span class="line">   List&lt;String&gt; aspectNames = <span class="keyword">this</span>.aspectBeanNames; <span class="comment">//他是怎么知道切面名字的</span></span><br><span class="line">   <span class="comment">//双检查锁的写法</span></span><br><span class="line">   <span class="keyword">if</span> (aspectNames == <span class="keyword">null</span>) &#123;</span><br><span class="line">      <span class="keyword">synchronized</span> (<span class="keyword">this</span>) &#123;</span><br><span class="line">         aspectNames = <span class="keyword">this</span>.aspectBeanNames;</span><br><span class="line">         <span class="keyword">if</span> (aspectNames == <span class="keyword">null</span>) &#123;</span><br><span class="line">            List&lt;Advisor&gt; advisors = <span class="keyword">new</span> ArrayList&lt;&gt;();</span><br><span class="line">            aspectNames = <span class="keyword">new</span> ArrayList&lt;&gt;();</span><br><span class="line">            String[] beanNames = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(</span><br><span class="line">                  <span class="keyword">this</span>.beanFactory, Object.class, <span class="keyword">true</span>, <span class="keyword">false</span>);</span><br><span class="line">            <span class="keyword">for</span> (String beanName : beanNames) &#123;</span><br><span class="line">               <span class="keyword">if</span> (!isEligibleBean(beanName)) &#123;</span><br><span class="line">                  <span class="keyword">continue</span>;</span><br><span class="line">               &#125;</span><br><span class="line">               <span class="comment">// We must be careful not to instantiate beans eagerly as in this case they</span></span><br><span class="line">               <span class="comment">// would be cached by the Spring container but would not have been weaved.</span></span><br><span class="line">               Class&lt;?&gt; beanType = <span class="keyword">this</span>.beanFactory.getType(beanName, <span class="keyword">false</span>);</span><br><span class="line">               <span class="keyword">if</span> (beanType == <span class="keyword">null</span>) &#123;</span><br><span class="line">                  <span class="keyword">continue</span>;</span><br><span class="line">               &#125;</span><br><span class="line">               <span class="keyword">if</span> (<span class="keyword">this</span>.advisorFactory.isAspect(beanType)) &#123;</span><br><span class="line">                  aspectNames.add(beanName); <span class="comment">//每一个组件都先判断是否是切面，如果是放在集合中</span></span><br><span class="line">                  AspectMetadata amd = <span class="keyword">new</span> AspectMetadata(beanType, beanName);</span><br><span class="line">                  <span class="keyword">if</span> (amd.getAjType().getPerClause().getKind() == PerClauseKind.SINGLETON) &#123;</span><br><span class="line">                     MetadataAwareAspectInstanceFactory factory =</span><br><span class="line">                           <span class="keyword">new</span> BeanFactoryAspectInstanceFactory(<span class="keyword">this</span>.beanFactory, beanName);</span><br><span class="line">                     List&lt;Advisor&gt; classAdvisors = <span class="keyword">this</span>.advisorFactory.getAdvisors(factory); <span class="comment">//获取增强器</span></span><br><span class="line">                     <span class="keyword">if</span> (<span class="keyword">this</span>.beanFactory.isSingleton(beanName)) &#123;</span><br><span class="line">                        <span class="keyword">this</span>.advisorsCache.put(beanName, classAdvisors);<span class="comment">//在第一次进入此方法的时候就把增强器放到缓存了</span></span><br><span class="line">                     &#125;</span><br><span class="line">                     <span class="keyword">else</span> &#123;</span><br><span class="line">                        <span class="keyword">this</span>.aspectFactoryCache.put(beanName, factory);</span><br><span class="line">                     &#125;</span><br><span class="line">                     advisors.addAll(classAdvisors);</span><br><span class="line">                  &#125;</span><br><span class="line">                  <span class="keyword">else</span> &#123;</span><br><span class="line">                     <span class="comment">// Per target or per this.</span></span><br><span class="line">                     <span class="keyword">if</span> (<span class="keyword">this</span>.beanFactory.isSingleton(beanName)) &#123;</span><br><span class="line">                        <span class="keyword">throw</span> <span class="keyword">new</span> IllegalArgumentException(<span class="string">&quot;Bean with name &#x27;&quot;</span> + beanName +</span><br><span class="line">                              <span class="string">&quot;&#x27; is a singleton, but aspect instantiation model is not singleton&quot;</span>);</span><br><span class="line">                     &#125;</span><br><span class="line">                     MetadataAwareAspectInstanceFactory factory =</span><br><span class="line">                           <span class="keyword">new</span> PrototypeAspectInstanceFactory(<span class="keyword">this</span>.beanFactory, beanName);</span><br><span class="line">                     <span class="keyword">this</span>.aspectFactoryCache.put(beanName, factory);</span><br><span class="line">                     advisors.addAll(<span class="keyword">this</span>.advisorFactory.getAdvisors(factory));</span><br><span class="line">                  &#125;</span><br><span class="line">               &#125;</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">this</span>.aspectBeanNames = aspectNames;</span><br><span class="line">            <span class="keyword">return</span> advisors;</span><br><span class="line">         &#125;</span><br><span class="line">      &#125;</span><br><span class="line">   &#125;</span><br><span class="line">		</span><br><span class="line">   <span class="comment">// 第二次进入此方法时，上面的if就不走了，直接跳到这里</span></span><br><span class="line">   <span class="keyword">if</span> (aspectNames.isEmpty()) &#123;</span><br><span class="line">      <span class="keyword">return</span> Collections.emptyList();</span><br><span class="line">   &#125;</span><br><span class="line">   List&lt;Advisor&gt; advisors = <span class="keyword">new</span> ArrayList&lt;&gt;(); <span class="comment">//</span></span><br><span class="line">   <span class="keyword">for</span> (String aspectName : aspectNames) &#123; <span class="comment">//遍历所有的切面找增强器</span></span><br><span class="line">      List&lt;Advisor&gt; cachedAdvisors = <span class="keyword">this</span>.advisorsCache.get(aspectName);</span><br><span class="line">      <span class="keyword">if</span> (cachedAdvisors != <span class="keyword">null</span>) &#123;</span><br><span class="line">         advisors.addAll(cachedAdvisors);</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="keyword">else</span> &#123;</span><br><span class="line">         MetadataAwareAspectInstanceFactory factory = <span class="keyword">this</span>.aspectFactoryCache.get(aspectName);</span><br><span class="line">         advisors.addAll(<span class="keyword">this</span>.advisorFactory.getAdvisors(factory));</span><br><span class="line">      &#125;</span><br><span class="line">   &#125;</span><br><span class="line">   <span class="keyword">return</span> advisors;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h4 id="结论-1"><a href="#结论-1" class="headerlink" title="结论"></a>结论</h4><blockquote>
<ol>
<li>registerBeanPostProcessors自此干完活了，后面就要走下面的代码了，创建其它Bean（也就是非后置处理器的这Bean）。我们重点看切入点HelloService和切面logAspect怎么创建的</li>
<li>注意，前面只是利用反射先分析准备好所有的信息，切面对象logAspect都没有创建</li>
</ol>
</blockquote>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="comment">//【大核心】bean创建；完成 BeanFactory 初始化。（工厂里面所有的组件都好了）</span></span><br><span class="line">finishBeanFactoryInitialization(beanFactory);</span><br></pre></td></tr></table></figure>

<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_06/image-20211012153225770.png" />

<h3 id="创建HelloService代理对象之前的工作"><a href="#创建HelloService代理对象之前的工作" class="headerlink" title="创建HelloService代理对象之前的工作"></a>创建HelloService代理对象之前的工作</h3><h4 id="创建对象"><a href="#创建对象" class="headerlink" title="创建对象"></a>创建对象</h4><p>我们在诸如下面的地方打上条件断点<code>beanName.equals(&quot;helloService&quot;) || beanName.equals(&quot;logAspect&quot;)</code></p>
<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_06/image-20211012153646657.png"/>

<p>debug放行</p>
<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_06/image-20211012154005700.png"/>



<p>往下走进入getBean()</p>
<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_06/image-20211012154205498.png"/>



<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_06/image-20211012154413318.png" />

<p>走到熟悉的createbean</p>
<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_06/image-20211012155231730.png"/>

<p>我们以前讲过resolveBeforeInstantiation是返回代理对象的机会，我们现在来看一下AOP有没有在这里给helloService返回代理对象。F7进入此方法</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">protected</span> Object <span class="title">resolveBeforeInstantiation</span><span class="params">(String beanName, RootBeanDefinition mbd)</span> </span>&#123;</span><br><span class="line">   Object bean = <span class="keyword">null</span>;</span><br><span class="line">   <span class="keyword">if</span> (!Boolean.FALSE.equals(mbd.beforeInstantiationResolved)) &#123;</span><br><span class="line">      <span class="comment">// Make sure bean class is actually resolved at this point.</span></span><br><span class="line">      <span class="keyword">if</span> (!mbd.isSynthetic() &amp;&amp; hasInstantiationAwareBeanPostProcessors()) &#123;</span><br><span class="line">         Class&lt;?&gt; targetType = determineTargetType(beanName, mbd);</span><br><span class="line">         <span class="keyword">if</span> (targetType != <span class="keyword">null</span>) &#123;</span><br><span class="line">            bean = applyBeanPostProcessorsBeforeInstantiation(targetType, beanName);</span><br><span class="line">            <span class="keyword">if</span> (bean != <span class="keyword">null</span>) &#123;</span><br><span class="line">               bean = applyBeanPostProcessorsAfterInitialization(bean, beanName);</span><br><span class="line">            &#125;</span><br><span class="line">         &#125;</span><br><span class="line">      &#125;</span><br><span class="line">      mbd.beforeInstantiationResolved = (bean != <span class="keyword">null</span>);</span><br><span class="line">   &#125;</span><br><span class="line">   <span class="keyword">return</span> bean;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_06/image-20211012160014471.png"/>

<p>这是有一个负责AOP功能的后置处理器，就是我们前面说的那个</p>
<p>当循环到这个后置处理器的时候，我们进入方法</p>
<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_06/image-20211012161510441.png"/>





<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_06/image-20211012161817522.png"/>



<p>我debug完之后发现前置过程啥也没干，返回了个NULL。什么都没干的原因就是<strong>负责AOP功能的后置处理器第一次运行准备好数据</strong>和<strong>构建增强器</strong>这两步已经干过了</p>
<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_06/image-20211012162158546.png"/>





<ol>
<li>最后我们惊奇的发现，AOP的后置处理器在resolveBeforeInstantiation这一步竟然没有返回代理对象，这可能跟大部分人想的有出入。</li>
<li>想一下为什么没有返回代理对象？走到这一步的时候，咱们的HelloService对象都还没有创建，更没有赋值，初始化。你如果在这里直接返回代理对象，那假设HelloService还注入了其它组件，那你返回的代理对象不就没有这些组件了嘛？直接跳过了。</li>
</ol>
<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_06/image-20211012163220063.png"/>

<p>往下走，创建一个最原始的对象</p>
<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_06/image-20211012165217922.png"  />

<h4 id="赋值"><a href="#赋值" class="headerlink" title="赋值"></a>赋值</h4><p>往下走进入赋值环节</p>
<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_06/image-20211012165702336.png" />

<p>我们来看下AOP的后置处理器在这一步有没有做事</p>
<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_06/image-20211012165933421.png"/>

<p>啥事没干，直接返回</p>
<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_06/image-20211012170025142.png"/>



<p>最后debug发现，整个赋值环节，AOP的后置处理器介入了，但是什么事都没干</p>
<h4 id="初始化"><a href="#初始化" class="headerlink" title="初始化"></a>初始化</h4><img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_06/image-20211012170944132.png"/>

<p>进入之后发现，AOP的后置处理器在此介入了，我们再进去看下到底做了啥</p>
<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_06/image-20211012171702722.png"/>

<p>啥也没做，直接返回原生Bean</p>
<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_06/image-20211012171813664.png" />



<ol>
<li>我Debug的时候也很吃惊，初始化的时候applyBeanPostProcessorsBeforeInitialization也没有返回代理对象，那到底何时返回的呢？</li>
<li>前置初始化没有做事，那我们看后置的初始化applyBeanPostProcessorsAfterInitialization</li>
</ol>
<h5 id="applyBeanPostProcessorsAfterInitialization后置初始化方法"><a href="#applyBeanPostProcessorsAfterInitialization后置初始化方法" class="headerlink" title="applyBeanPostProcessorsAfterInitialization后置初始化方法"></a>applyBeanPostProcessorsAfterInitialization后置初始化方法</h5><img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_06/image-20211012172107405.png"  />



<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_06/image-20211012172308103.png"/>

<p>F7进入方法</p>
<h5 id="AbstractAutoProxyCreator-postProcessAfterInitialization"><a href="#AbstractAutoProxyCreator-postProcessAfterInitialization" class="headerlink" title="AbstractAutoProxyCreator#postProcessAfterInitialization()"></a>AbstractAutoProxyCreator#postProcessAfterInitialization()</h5><blockquote>
<p>终于干活了</p>
</blockquote>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line">   <span class="meta">@Override</span></span><br><span class="line">   <span class="function"><span class="keyword">public</span> Object <span class="title">postProcessAfterInitialization</span><span class="params">(<span class="meta">@Nullable</span> Object bean, String beanName)</span> </span>&#123;</span><br><span class="line">      <span class="keyword">if</span> (bean != <span class="keyword">null</span>) &#123;</span><br><span class="line">         Object cacheKey = getCacheKey(bean.getClass(), beanName);</span><br><span class="line">          <span class="comment">// 这里的意思是，如果之前创建过早期代理对象就直接返回了，不给我们再创建了</span></span><br><span class="line">         <span class="keyword">if</span> (<span class="keyword">this</span>.earlyProxyReferences.remove(cacheKey) != bean) &#123;</span><br><span class="line">            <span class="keyword">return</span> wrapIfNecessary(bean, beanName, cacheKey);</span><br><span class="line">         &#125;</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="keyword">return</span> bean;</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">protected</span> Object <span class="title">wrapIfNecessary</span><span class="params">(Object bean, String beanName, Object cacheKey)</span> </span>&#123;</span><br><span class="line">	<span class="keyword">if</span> (StringUtils.hasLength(beanName) &amp;&amp; <span class="keyword">this</span>.targetSourcedBeans.contains(beanName)) &#123;</span><br><span class="line">		<span class="keyword">return</span> bean;</span><br><span class="line">	&#125;</span><br><span class="line">        <span class="comment">// 前面说的advisedBeans在这里会干活了，如果此时beanName是logAspect，这里会直接返回，不会走下面的代理逻辑，</span></span><br><span class="line">	<span class="keyword">if</span> (Boolean.FALSE.equals(<span class="keyword">this</span>.advisedBeans.get(cacheKey))) &#123;</span><br><span class="line">		<span class="keyword">return</span> bean;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">if</span> (isInfrastructureClass(bean.getClass()) || shouldSkip(bean.getClass(), beanName)) &#123;</span><br><span class="line">		<span class="keyword">this</span>.advisedBeans.put(cacheKey, Boolean.FALSE);</span><br><span class="line">		<span class="keyword">return</span> bean;</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="comment">//如果有切面的通知方法切入这个对象，就给对象创建代理 Create proxy if we have advice.</span></span><br><span class="line">	Object[] specificInterceptors = getAdvicesAndAdvisorsForBean(bean.getClass(), beanName, <span class="keyword">null</span>);</span><br><span class="line">	<span class="keyword">if</span> (specificInterceptors != DO_NOT_PROXY) &#123;</span><br><span class="line">		<span class="keyword">this</span>.advisedBeans.put(cacheKey, Boolean.TRUE);</span><br><span class="line">		Object proxy = createProxy(</span><br><span class="line">				bean.getClass(), beanName, specificInterceptors, <span class="keyword">new</span> SingletonTargetSource(bean));</span><br><span class="line">		<span class="keyword">this</span>.proxyTypes.put(cacheKey, proxy.getClass());</span><br><span class="line">		<span class="keyword">return</span> proxy;</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="keyword">this</span>.advisedBeans.put(cacheKey, Boolean.FALSE);</span><br><span class="line">	<span class="keyword">return</span> bean;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h5 id="AbstractAdvisorAutoProxyCreator-findEligibleAdvisors-是否有切面切入这个bean"><a href="#AbstractAdvisorAutoProxyCreator-findEligibleAdvisors-是否有切面切入这个bean" class="headerlink" title="AbstractAdvisorAutoProxyCreator#findEligibleAdvisors()是否有切面切入这个bean"></a>AbstractAdvisorAutoProxyCreator#findEligibleAdvisors()是否有切面切入这个bean</h5><figure class="highlight java"><table><tr><td class="code"><pre><span class="line">   <span class="meta">@Override</span></span><br><span class="line">   <span class="meta">@Nullable</span></span><br><span class="line">   <span class="keyword">protected</span> Object[] getAdvicesAndAdvisorsForBean(</span><br><span class="line">         Class&lt;?&gt; beanClass, String beanName, <span class="meta">@Nullable</span> TargetSource targetSource) &#123;</span><br><span class="line">      <span class="comment">//找到所有合适这个类的 Advisor</span></span><br><span class="line">      List&lt;Advisor&gt; advisors = findEligibleAdvisors(beanClass, beanName);</span><br><span class="line">      <span class="keyword">if</span> (advisors.isEmpty()) &#123;</span><br><span class="line">         <span class="keyword">return</span> DO_NOT_PROXY;</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="keyword">return</span> advisors.toArray();</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">protected</span> List&lt;Advisor&gt; <span class="title">findEligibleAdvisors</span><span class="params">(Class&lt;?&gt; beanClass, String beanName)</span> </span>&#123;</span><br><span class="line">	List&lt;Advisor&gt; candidateAdvisors = findCandidateAdvisors(); <span class="comment">//缓存中直接就会有</span></span><br><span class="line">	List&lt;Advisor&gt; eligibleAdvisors = findAdvisorsThatCanApply(candidateAdvisors, beanClass, beanName); <span class="comment">//看增强器能不能应用到这个对象上</span></span><br><span class="line">	extendAdvisors(eligibleAdvisors);</span><br><span class="line">	<span class="keyword">if</span> (!eligibleAdvisors.isEmpty()) &#123;</span><br><span class="line">		eligibleAdvisors = sortAdvisors(eligibleAdvisors);</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">return</span> eligibleAdvisors;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">protected</span> List&lt;Advisor&gt; <span class="title">findAdvisorsThatCanApply</span><span class="params">(</span></span></span><br><span class="line"><span class="function"><span class="params">		List&lt;Advisor&gt; candidateAdvisors, Class&lt;?&gt; beanClass, String beanName)</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">	ProxyCreationContext.setCurrentProxiedBeanName(beanName);</span><br><span class="line">	<span class="keyword">try</span> &#123;</span><br><span class="line">		<span class="keyword">return</span> AopUtils.findAdvisorsThatCanApply(candidateAdvisors, beanClass);</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">finally</span> &#123;</span><br><span class="line">		ProxyCreationContext.setCurrentProxiedBeanName(<span class="keyword">null</span>);</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>我发现他调用了咱们之前讲过的方法</p>
<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_06/image-20211012173003595.png"  />

<p>因为之前调用过，缓存中有，直接返回</p>
<h5 id="AopUtils-findAdvisorsThatCanApply-正则解析切面表达式判断是否能切入"><a href="#AopUtils-findAdvisorsThatCanApply-正则解析切面表达式判断是否能切入" class="headerlink" title="AopUtils#findAdvisorsThatCanApply()正则解析切面表达式判断是否能切入"></a>AopUtils#findAdvisorsThatCanApply()正则解析切面表达式判断是否能切入</h5><figure class="highlight java"><table><tr><td class="code"><pre><span class="line">   <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> List&lt;Advisor&gt; <span class="title">findAdvisorsThatCanApply</span><span class="params">(List&lt;Advisor&gt; candidateAdvisors, Class&lt;?&gt; clazz)</span> </span>&#123;</span><br><span class="line">      <span class="keyword">if</span> (candidateAdvisors.isEmpty()) &#123;</span><br><span class="line">         <span class="keyword">return</span> candidateAdvisors;</span><br><span class="line">      &#125;</span><br><span class="line">      List&lt;Advisor&gt; eligibleAdvisors = <span class="keyword">new</span> ArrayList&lt;&gt;();</span><br><span class="line">      <span class="keyword">for</span> (Advisor candidate : candidateAdvisors) &#123;</span><br><span class="line">         <span class="keyword">if</span> (candidate <span class="keyword">instanceof</span> IntroductionAdvisor &amp;&amp; canApply(candidate, clazz)) &#123;</span><br><span class="line">            eligibleAdvisors.add(candidate);</span><br><span class="line">         &#125;</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="keyword">boolean</span> hasIntroductions = !eligibleAdvisors.isEmpty();</span><br><span class="line">      <span class="keyword">for</span> (Advisor candidate : candidateAdvisors) &#123;</span><br><span class="line">         <span class="keyword">if</span> (candidate <span class="keyword">instanceof</span> IntroductionAdvisor) &#123;</span><br><span class="line">            <span class="comment">// already processed</span></span><br><span class="line">            <span class="keyword">continue</span>;</span><br><span class="line">         &#125;</span><br><span class="line">         <span class="keyword">if</span> (canApply(candidate, clazz, hasIntroductions)) &#123;</span><br><span class="line">            eligibleAdvisors.add(candidate);</span><br><span class="line">         &#125;</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="keyword">return</span> eligibleAdvisors;</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">boolean</span> <span class="title">canApply</span><span class="params">(Advisor advisor, Class&lt;?&gt; targetClass, <span class="keyword">boolean</span> hasIntroductions)</span> </span>&#123;</span><br><span class="line">	<span class="keyword">if</span> (advisor <span class="keyword">instanceof</span> IntroductionAdvisor) &#123;</span><br><span class="line">		<span class="keyword">return</span> ((IntroductionAdvisor) advisor).getClassFilter().matches(targetClass);</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">else</span> <span class="keyword">if</span> (advisor <span class="keyword">instanceof</span> PointcutAdvisor) &#123;</span><br><span class="line">		PointcutAdvisor pca = (PointcutAdvisor) advisor;</span><br><span class="line">		<span class="keyword">return</span> canApply(pca.getPointcut(), targetClass, hasIntroductions);</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">else</span> &#123;</span><br><span class="line">		<span class="comment">// It doesn&#x27;t have a pointcut so we assume it applies.</span></span><br><span class="line">		<span class="keyword">return</span> <span class="keyword">true</span>;</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_06/image-20211012173631784.png"/>



<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">boolean</span> <span class="title">canApply</span><span class="params">(Pointcut pc, Class&lt;?&gt; targetClass, <span class="keyword">boolean</span> hasIntroductions)</span> </span>&#123;</span><br><span class="line">   Assert.notNull(pc, <span class="string">&quot;Pointcut must not be null&quot;</span>);</span><br><span class="line">   <span class="keyword">if</span> (!pc.getClassFilter().matches(targetClass)) &#123;</span><br><span class="line">      <span class="keyword">return</span> <span class="keyword">false</span>;</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">   MethodMatcher methodMatcher = pc.getMethodMatcher();</span><br><span class="line">   <span class="keyword">if</span> (methodMatcher == MethodMatcher.TRUE) &#123;</span><br><span class="line">      <span class="comment">// No need to iterate the methods if we&#x27;re matching any method anyway...</span></span><br><span class="line">      <span class="keyword">return</span> <span class="keyword">true</span>;</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">   IntroductionAwareMethodMatcher introductionAwareMethodMatcher = <span class="keyword">null</span>;</span><br><span class="line">   <span class="keyword">if</span> (methodMatcher <span class="keyword">instanceof</span> IntroductionAwareMethodMatcher) &#123;</span><br><span class="line">      introductionAwareMethodMatcher = (IntroductionAwareMethodMatcher) methodMatcher;</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">   Set&lt;Class&lt;?&gt;&gt; classes = <span class="keyword">new</span> LinkedHashSet&lt;&gt;();</span><br><span class="line">   <span class="keyword">if</span> (!Proxy.isProxyClass(targetClass)) &#123;</span><br><span class="line">      classes.add(ClassUtils.getUserClass(targetClass));</span><br><span class="line">   &#125;</span><br><span class="line">   classes.addAll(ClassUtils.getAllInterfacesForClassAsSet(targetClass));</span><br><span class="line"></span><br><span class="line">   <span class="keyword">for</span> (Class&lt;?&gt; clazz : classes) &#123;</span><br><span class="line">      Method[] methods = ReflectionUtils.getAllDeclaredMethods(clazz);</span><br><span class="line">      <span class="keyword">for</span> (Method method : methods) &#123;</span><br><span class="line">         <span class="comment">//下面就是正则解析的流程了，不细讲了</span></span><br><span class="line">         <span class="keyword">if</span> (introductionAwareMethodMatcher != <span class="keyword">null</span> ?</span><br><span class="line">               introductionAwareMethodMatcher.matches(method, targetClass, hasIntroductions) :</span><br><span class="line">               methodMatcher.matches(method, targetClass)) &#123;</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">true</span>;</span><br><span class="line">         &#125;</span><br><span class="line">      &#125;</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">   <span class="keyword">return</span> <span class="keyword">false</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h5 id="返回到AbstractAdvisorAutoProxyCreator-findEligibleAdvisors"><a href="#返回到AbstractAdvisorAutoProxyCreator-findEligibleAdvisors" class="headerlink" title="返回到AbstractAdvisorAutoProxyCreator#findEligibleAdvisors()"></a>返回到AbstractAdvisorAutoProxyCreator#findEligibleAdvisors()</h5><p>接着我们返回到这一步，看到了这几个增强器</p>
<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_06/image-20211012174251200.png"  />

<p>这里又有一个重要方法</p>
<h5 id="AspectJAwareAdvisorAutoProxyCreator-extendAdvisors"><a href="#AspectJAwareAdvisorAutoProxyCreator-extendAdvisors" class="headerlink" title="AspectJAwareAdvisorAutoProxyCreator#extendAdvisors()"></a>AspectJAwareAdvisorAutoProxyCreator#extendAdvisors()</h5><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">extendAdvisors</span><span class="params">(List&lt;Advisor&gt; candidateAdvisors)</span> </span>&#123;</span><br><span class="line">   AspectJProxyUtils.makeAdvisorChainAspectJCapableIfNecessary(candidateAdvisors);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h5 id="AspectJProxyUtils-makeAdvisorChainAspectJCapableIfNecessary-创建增强器链"><a href="#AspectJProxyUtils-makeAdvisorChainAspectJCapableIfNecessary-创建增强器链" class="headerlink" title="AspectJProxyUtils#makeAdvisorChainAspectJCapableIfNecessary()创建增强器链"></a>AspectJProxyUtils#makeAdvisorChainAspectJCapableIfNecessary()创建增强器链</h5><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="comment">//创建增强器链</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">boolean</span> <span class="title">makeAdvisorChainAspectJCapableIfNecessary</span><span class="params">(List&lt;Advisor&gt; advisors)</span> </span>&#123;</span><br><span class="line">   <span class="comment">// Don&#x27;t add advisors to an empty list; may indicate that proxying is just not required</span></span><br><span class="line">   <span class="keyword">if</span> (!advisors.isEmpty()) &#123;</span><br><span class="line">      <span class="keyword">boolean</span> foundAspectJAdvice = <span class="keyword">false</span>;</span><br><span class="line">      <span class="keyword">for</span> (Advisor advisor : advisors) &#123;</span><br><span class="line">         <span class="comment">// Be careful not to get the Advice without a guard, as this might eagerly</span></span><br><span class="line">         <span class="comment">// instantiate a non-singleton AspectJ aspect...</span></span><br><span class="line">         <span class="keyword">if</span> (isAspectJAdvice(advisor)) &#123;</span><br><span class="line">            foundAspectJAdvice = <span class="keyword">true</span>;</span><br><span class="line">            <span class="keyword">break</span>;</span><br><span class="line">         &#125;</span><br><span class="line">      &#125; <span class="comment">//链里面添加了个ExposeInvocationInterceptor（拦截器）</span></span><br><span class="line">      <span class="keyword">if</span> (foundAspectJAdvice &amp;&amp; !advisors.contains(ExposeInvocationInterceptor.ADVISOR)) &#123;</span><br><span class="line">         advisors.add(<span class="number">0</span>, ExposeInvocationInterceptor.ADVISOR);</span><br><span class="line">         <span class="keyword">return</span> <span class="keyword">true</span>;</span><br><span class="line">      &#125;</span><br><span class="line">   &#125;</span><br><span class="line">   <span class="keyword">return</span> <span class="keyword">false</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_06/image-20211012174626015.png"  />

<p>回到AbstractAutoProxyCreator#wrapIfNecessary，调用下面的方法真正开始创建代理对象</p>
<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_06/image-20211012191915487.png"/>

<h5 id="AbstractAutoProxyCreator-createProxy-开始创建代理对象"><a href="#AbstractAutoProxyCreator-createProxy-开始创建代理对象" class="headerlink" title="AbstractAutoProxyCreator#createProxy()开始创建代理对象"></a>AbstractAutoProxyCreator#createProxy()开始创建代理对象</h5><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">protected</span> Object <span class="title">createProxy</span><span class="params">(Class&lt;?&gt; beanClass, <span class="meta">@Nullable</span> String beanName,</span></span></span><br><span class="line"><span class="function"><span class="params">      <span class="meta">@Nullable</span> Object[] specificInterceptors, TargetSource targetSource)</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">   <span class="keyword">if</span> (<span class="keyword">this</span>.beanFactory <span class="keyword">instanceof</span> ConfigurableListableBeanFactory) &#123;</span><br><span class="line">      AutoProxyUtils.exposeTargetClass((ConfigurableListableBeanFactory) <span class="keyword">this</span>.beanFactory, beanName, beanClass);</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">   ProxyFactory proxyFactory = <span class="keyword">new</span> ProxyFactory();</span><br><span class="line">   proxyFactory.copyFrom(<span class="keyword">this</span>);</span><br><span class="line"></span><br><span class="line">   <span class="keyword">if</span> (!proxyFactory.isProxyTargetClass()) &#123;</span><br><span class="line">      <span class="keyword">if</span> (shouldProxyTargetClass(beanClass, beanName)) &#123;</span><br><span class="line">         proxyFactory.setProxyTargetClass(<span class="keyword">true</span>);</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="keyword">else</span> &#123;</span><br><span class="line">         evaluateProxyInterfaces(beanClass, proxyFactory);</span><br><span class="line">      &#125;</span><br><span class="line">   &#125;</span><br><span class="line">       <span class="comment">//构建增强器</span></span><br><span class="line">   Advisor[] advisors = buildAdvisors(beanName, specificInterceptors);</span><br><span class="line">   proxyFactory.addAdvisors(advisors);</span><br><span class="line">   proxyFactory.setTargetSource(targetSource);</span><br><span class="line">   customizeProxyFactory(proxyFactory);</span><br><span class="line"></span><br><span class="line">   proxyFactory.setFrozen(<span class="keyword">this</span>.freezeProxy);</span><br><span class="line">   <span class="keyword">if</span> (advisorsPreFiltered()) &#123;</span><br><span class="line">      proxyFactory.setPreFiltered(<span class="keyword">true</span>);</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">   <span class="keyword">return</span> proxyFactory.getProxy(getProxyClassLoader());</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h5 id="ProxyFactory-getProxy"><a href="#ProxyFactory-getProxy" class="headerlink" title="ProxyFactory#getProxy()"></a>ProxyFactory#getProxy()</h5><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> Object <span class="title">getProxy</span><span class="params">(<span class="meta">@Nullable</span> ClassLoader classLoader)</span> </span>&#123;</span><br><span class="line">   <span class="keyword">return</span> createAopProxy().getProxy(classLoader);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h5 id="ProxyCreatorSupport-createAopProxy"><a href="#ProxyCreatorSupport-createAopProxy" class="headerlink" title="ProxyCreatorSupport#createAopProxy()"></a>ProxyCreatorSupport#createAopProxy()</h5><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">protected</span> <span class="keyword">final</span> <span class="keyword">synchronized</span> AopProxy <span class="title">createAopProxy</span><span class="params">()</span> </span>&#123;</span><br><span class="line">   <span class="keyword">if</span> (!<span class="keyword">this</span>.active) &#123;</span><br><span class="line">      activate();</span><br><span class="line">   &#125;</span><br><span class="line">   <span class="keyword">return</span> getAopProxyFactory().createAopProxy(<span class="keyword">this</span>);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h5 id="DefaultAopProxyFactory-createAopProxy"><a href="#DefaultAopProxyFactory-createAopProxy" class="headerlink" title="DefaultAopProxyFactory#createAopProxy()"></a>DefaultAopProxyFactory#createAopProxy()</h5><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> AopProxy <span class="title">createAopProxy</span><span class="params">(AdvisedSupport config)</span> <span class="keyword">throws</span> AopConfigException </span>&#123;</span><br><span class="line">   <span class="keyword">if</span> (!NativeDetector.inNativeImage() &amp;&amp;</span><br><span class="line">         (config.isOptimize() || config.isProxyTargetClass() || hasNoUserSuppliedProxyInterfaces(config))) &#123;</span><br><span class="line">      Class&lt;?&gt; targetClass = config.getTargetClass();</span><br><span class="line">      <span class="keyword">if</span> (targetClass == <span class="keyword">null</span>) &#123;</span><br><span class="line">         <span class="keyword">throw</span> <span class="keyword">new</span> AopConfigException(<span class="string">&quot;TargetSource cannot determine target class: &quot;</span> +</span><br><span class="line">               <span class="string">&quot;Either an interface or a target is required for proxy creation.&quot;</span>);</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="keyword">if</span> (targetClass.isInterface() || Proxy.isProxyClass(targetClass)) &#123;</span><br><span class="line">         <span class="keyword">return</span> <span class="keyword">new</span> JdkDynamicAopProxy(config);</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="keyword">return</span> <span class="keyword">new</span> ObjenesisCglibAopProxy(config);</span><br><span class="line">   &#125;</span><br><span class="line">   <span class="keyword">else</span> &#123;</span><br><span class="line">      <span class="keyword">return</span> <span class="keyword">new</span> JdkDynamicAopProxy(config);</span><br><span class="line">   &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>要么是cglib的代理要么是jdk的代理</p>
<h5 id="CglibAopProxy-getProxy"><a href="#CglibAopProxy-getProxy" class="headerlink" title="CglibAopProxy#getProxy()"></a>CglibAopProxy#getProxy()</h5><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> Object <span class="title">getProxy</span><span class="params">(<span class="meta">@Nullable</span> ClassLoader classLoader)</span> </span>&#123;</span><br><span class="line">   <span class="keyword">if</span> (logger.isTraceEnabled()) &#123;</span><br><span class="line">      logger.trace(<span class="string">&quot;Creating CGLIB proxy: &quot;</span> + <span class="keyword">this</span>.advised.getTargetSource());</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">   <span class="keyword">try</span> &#123;</span><br><span class="line">      Class&lt;?&gt; rootClass = <span class="keyword">this</span>.advised.getTargetClass();</span><br><span class="line">      Assert.state(rootClass != <span class="keyword">null</span>, <span class="string">&quot;Target class must be available for creating a CGLIB proxy&quot;</span>);</span><br><span class="line"></span><br><span class="line">      Class&lt;?&gt; proxySuperClass = rootClass;</span><br><span class="line">      <span class="keyword">if</span> (rootClass.getName().contains(ClassUtils.CGLIB_CLASS_SEPARATOR)) &#123;</span><br><span class="line">         proxySuperClass = rootClass.getSuperclass();</span><br><span class="line">         Class&lt;?&gt;[] additionalInterfaces = rootClass.getInterfaces();</span><br><span class="line">         <span class="keyword">for</span> (Class&lt;?&gt; additionalInterface : additionalInterfaces) &#123;</span><br><span class="line">            <span class="keyword">this</span>.advised.addInterface(additionalInterface);</span><br><span class="line">         &#125;</span><br><span class="line">      &#125;</span><br><span class="line"></span><br><span class="line">      <span class="comment">// Validate the class, writing log messages as necessary.</span></span><br><span class="line">      validateClassIfNecessary(proxySuperClass, classLoader);</span><br><span class="line"></span><br><span class="line">      <span class="comment">// Configure CGLIB Enhancer...</span></span><br><span class="line">      Enhancer enhancer = createEnhancer();</span><br><span class="line">      <span class="keyword">if</span> (classLoader != <span class="keyword">null</span>) &#123;</span><br><span class="line">         enhancer.setClassLoader(classLoader);</span><br><span class="line">         <span class="keyword">if</span> (classLoader <span class="keyword">instanceof</span> SmartClassLoader &amp;&amp;</span><br><span class="line">               ((SmartClassLoader) classLoader).isClassReloadable(proxySuperClass)) &#123;</span><br><span class="line">            enhancer.setUseCache(<span class="keyword">false</span>);</span><br><span class="line">         &#125;</span><br><span class="line">      &#125;</span><br><span class="line">      enhancer.setSuperclass(proxySuperClass);</span><br><span class="line">      enhancer.setInterfaces(AopProxyUtils.completeProxiedInterfaces(<span class="keyword">this</span>.advised));</span><br><span class="line">      enhancer.setNamingPolicy(SpringNamingPolicy.INSTANCE);</span><br><span class="line">      enhancer.setStrategy(<span class="keyword">new</span> ClassLoaderAwareGeneratorStrategy(classLoader));</span><br><span class="line"></span><br><span class="line">      Callback[] callbacks = getCallbacks(rootClass);</span><br><span class="line">      Class&lt;?&gt;[] types = <span class="keyword">new</span> Class&lt;?&gt;[callbacks.length];</span><br><span class="line">      <span class="keyword">for</span> (<span class="keyword">int</span> x = <span class="number">0</span>; x &lt; types.length; x++) &#123;</span><br><span class="line">         types[x] = callbacks[x].getClass();</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="comment">// fixedInterceptorMap only populated at this point, after getCallbacks call above</span></span><br><span class="line">      enhancer.setCallbackFilter(<span class="keyword">new</span> ProxyCallbackFilter(</span><br><span class="line">            <span class="keyword">this</span>.advised.getConfigurationOnlyCopy(), <span class="keyword">this</span>.fixedInterceptorMap, <span class="keyword">this</span>.fixedInterceptorOffset));</span><br><span class="line">      enhancer.setCallbackTypes(types);</span><br><span class="line"></span><br><span class="line">      <span class="comment">// Generate the proxy class and create a proxy instance.</span></span><br><span class="line">      <span class="keyword">return</span> createProxyClassAndInstance(enhancer, callbacks);</span><br><span class="line">   &#125;</span><br><span class="line">   <span class="keyword">catch</span> (CodeGenerationException | IllegalArgumentException ex) &#123;</span><br><span class="line">      <span class="keyword">throw</span> <span class="keyword">new</span> AopConfigException(<span class="string">&quot;Could not generate CGLIB subclass of &quot;</span> + <span class="keyword">this</span>.advised.getTargetClass() +</span><br><span class="line">            <span class="string">&quot;: Common causes of this problem include using a final class or a non-visible class&quot;</span>,</span><br><span class="line">            ex);</span><br><span class="line">   &#125;</span><br><span class="line">   <span class="keyword">catch</span> (Throwable ex) &#123;</span><br><span class="line">      <span class="comment">// TargetSource.getTarget() failed</span></span><br><span class="line">      <span class="keyword">throw</span> <span class="keyword">new</span> AopConfigException(<span class="string">&quot;Unexpected AOP exception&quot;</span>, ex);</span><br><span class="line">   &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h5 id="HelloService代理对象创建完成"><a href="#HelloService代理对象创建完成" class="headerlink" title="HelloService代理对象创建完成"></a>HelloService代理对象创建完成</h5><p>最后返回</p>
<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_06/image-20211012193828795.png" />



<p>继续返回</p>
<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_06/image-20211012194036836.png"/>



<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_06/image-20211012194217705.png"/>

<p>最终单例池里就有代理对象了</p>
<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_06/image-20211012194446377.png"/>

<h5 id="logAspect创建原生对象，而不是代理对象"><a href="#logAspect创建原生对象，而不是代理对象" class="headerlink" title="logAspect创建原生对象，而不是代理对象"></a>logAspect创建原生对象，而不是代理对象</h5><p>logAspect切面对象最后创建的是原生对象，如下图，因为他不需要代理</p>
<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_06/image-20211012194718066.png"  />



<blockquote>
<p>自此，负责AOP的后置处理器和代理对象创建过程讲完了，下一章讲AOP执行流程。</p>
</blockquote>
</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="mailto:undefined">youthlql</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="https://imlql.cn/post/598f6b0d.html">https://imlql.cn/post/598f6b0d.html</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="https://imlql.cn" target="_blank">风祈的时光录</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/Spring%E6%BA%90%E7%A0%81/">Spring源码</a></div><div class="post_share"></div></div><div class="post-reward"><div class="reward-button"><i class="fas fa-qrcode"></i> 打赏</div><div class="reward-main"><ul class="reward-all"><li class="reward-item"><a href="https://npm.elemecdn.com/youthlql@1.0.8/blog/wechat.jpg" target="_blank"><img class="post-qr-code-img" src= "" data-lazy-src="https://npm.elemecdn.com/youthlql@1.0.8/blog/wechat.jpg" alt="微信"/></a><div class="post-qr-code-desc">微信</div></li><li class="reward-item"><a href="https://npm.elemecdn.com/youthlql@1.0.8/blog/alipay.jpg" target="_blank"><img class="post-qr-code-img" src= "" data-lazy-src="https://npm.elemecdn.com/youthlql@1.0.8/blog/alipay.jpg" alt="支付宝"/></a><div class="post-qr-code-desc">支付宝</div></li></ul></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/post/fb3552e0.html"><img class="prev-cover" src= "" data-lazy-src="https://npm.elemecdn.com/lql_static@latest/logo/spring.png" onerror="onerror=null;src='/img/404.jpg'" alt="cover of previous post"><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">Spring源码系列-第7章-AOP的执行流程原理和监听器原理</div></div></a></div><div class="next-post pull-right"><a href="/post/a1b8c236.html"><img class="next-cover" src= "" data-lazy-src="https://npm.elemecdn.com/lql_static@latest/logo/spring.png" onerror="onerror=null;src='/img/404.jpg'" alt="cover of next post"><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">Spring源码系列-第5章-容器刷新流程</div></div></a></div></nav><div class="relatedPosts"><div class="headline"><i class="fas fa-thumbs-up fa-fw"></i><span>相关推荐</span></div><div class="relatedPosts-list"><div><a href="/post/41fb8d9e.html" title="Spring源码系列-第2章-后置工厂处理器和Bean生命周期"><img class="cover" src= "" data-lazy-src="https://npm.elemecdn.com/lql_static@latest/logo/spring.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2021-12-21</div><div class="title">Spring源码系列-第2章-后置工厂处理器和Bean生命周期</div></div></a></div><div><a href="/post/49f419ae.html" title="Spring源码系列-第4章-Bean初始化流程"><img class="cover" src= "" data-lazy-src="https://npm.elemecdn.com/lql_static@latest/logo/spring.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-01-27</div><div class="title">Spring源码系列-第4章-Bean初始化流程</div></div></a></div><div><a href="/post/fb3552e0.html" title="Spring源码系列-第7章-AOP的执行流程原理和监听器原理"><img class="cover" src= "" data-lazy-src="https://npm.elemecdn.com/lql_static@latest/logo/spring.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-04-17</div><div class="title">Spring源码系列-第7章-AOP的执行流程原理和监听器原理</div></div></a></div><div><a href="/post/c8dd1418.html" title="Spring源码系列-第8章-SpringMVC子容器和Spring父容器的启动原理"><img class="cover" src= "" data-lazy-src="https://npm.elemecdn.com/lql_static@latest/logo/spring.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-06-20</div><div class="title">Spring源码系列-第8章-SpringMVC子容器和Spring父容器的启动原理</div></div></a></div><div><a href="/post/6f2cef28.html" title="Spring源码系列-第9章-SpringMVC请求处理源码和HandlerMapping原理"><img class="cover" src= "" data-lazy-src="https://npm.elemecdn.com/lql_static@latest/logo/spring.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-06-21</div><div class="title">Spring源码系列-第9章-SpringMVC请求处理源码和HandlerMapping原理</div></div></a></div><div><a href="/post/4dfb096b.html" title="Spring源码系列-第11章-SpringMVC异常处理源码和@EnableWebMvc原理"><img class="cover" src= "" data-lazy-src="https://npm.elemecdn.com/lql_static@latest/logo/spring.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2023-01-05</div><div class="title">Spring源码系列-第11章-SpringMVC异常处理源码和@EnableWebMvc原理</div></div></a></div></div></div></div><div class="aside-content" id="aside-content"><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span><span class="toc-percentage"></span></div><div class="toc-content is-expand"><ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#%E7%AC%AC6%E7%AB%A0-AOP%E7%9A%84%E5%90%8E%E7%BD%AE%E5%A4%84%E7%90%86%E5%99%A8%E5%92%8C%E4%BB%A3%E7%90%86%E5%AF%B9%E8%B1%A1%E7%9A%84%E5%88%9B%E5%BB%BA"><span class="toc-text">第6章-AOP的后置处理器和代理对象的创建</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%B5%8B%E8%AF%95%E7%B1%BB"><span class="toc-text">测试类</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#MainConfig"><span class="toc-text">MainConfig</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#AopOpenConfig"><span class="toc-text">AopOpenConfig</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#LogAspect"><span class="toc-text">LogAspect</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#HelloService"><span class="toc-text">HelloService</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#AnnotationMainTest"><span class="toc-text">AnnotationMainTest</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%A6%82%E4%BD%95%E5%88%86%E6%9E%90Spring%E7%9A%84%E4%B8%80%E4%B8%AA%E6%96%B0%E5%8A%9F%E8%83%BD"><span class="toc-text">如何分析Spring的一个新功能</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%88%86%E6%9E%90-EnableXXX%E6%89%BE%E5%88%B0%E8%B4%9F%E8%B4%A3AOP%E5%8A%9F%E8%83%BD%E7%9A%84%E5%90%8E%E7%BD%AE%E5%A4%84%E7%90%86%E5%99%A8"><span class="toc-text">分析@EnableXXX找到负责AOP功能的后置处理器</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#EnableAspectJAutoProxy"><span class="toc-text">@EnableAspectJAutoProxy</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#AspectJAutoProxyRegistrar-registerBeanDefinitions"><span class="toc-text">AspectJAutoProxyRegistrar#registerBeanDefinitions()</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#Debug%E8%B0%83%E7%94%A8%E6%A0%88"><span class="toc-text">Debug调用栈</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#ImportBeanDefinitionRegistrar"><span class="toc-text">ImportBeanDefinitionRegistrar</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#AopConfigUtils-registerAspectJAnnotationAutoProxyCreatorIfNecessary%E6%B3%A8%E5%86%8C%E5%88%87%E9%9D%A2%E7%9A%84%E5%9F%BA%E4%BA%8E%E6%B3%A8%E8%A7%A3%E7%9A%84%E8%87%AA%E5%8A%A8%E4%BB%A3%E7%90%86%E5%88%9B%E5%BB%BA%E5%99%A8"><span class="toc-text">AopConfigUtils#registerAspectJAnnotationAutoProxyCreatorIfNecessary注册切面的基于注解的自动代理创建器</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#AnnotationAwareAspectJAutoProxyCreator%E5%90%8E%E7%BD%AE%E5%A4%84%E7%90%86%E5%99%A8"><span class="toc-text">AnnotationAwareAspectJAutoProxyCreator后置处理器</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#AnnotationAwareAspectJAutoProxyCreator%E5%9C%A8%E7%94%9F%E5%91%BD%E5%91%A8%E6%9C%9F%E6%9C%9F%E9%97%B4%E5%81%9A%E4%BA%86%E4%BB%80%E4%B9%88%E4%BA%8B%EF%BC%9F"><span class="toc-text">AnnotationAwareAspectJAutoProxyCreator在生命周期期间做了什么事？</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%80%8E%E4%B9%88%E5%88%86%E6%9E%90%EF%BC%9F"><span class="toc-text">怎么分析？</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E8%B4%9F%E8%B4%A3AOP%E5%8A%9F%E8%83%BD%E7%9A%84%E5%90%8E%E7%BD%AE%E5%A4%84%E7%90%86%E5%99%A8%E7%AC%AC%E4%B8%80%E6%AC%A1%E8%BF%90%E8%A1%8C%E5%87%86%E5%A4%87%E5%A5%BD%E6%95%B0%E6%8D%AE"><span class="toc-text">负责AOP功能的后置处理器第一次运行准备好数据</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#Debug%E8%B0%83%E7%94%A8%E6%A0%88-%E8%B0%83%E7%94%A8AnnotationAwareAspectJAutoProxyCreator%E7%9A%84initBeanFactory-%E6%96%B9%E6%B3%95%E5%88%9D%E5%A7%8B%E5%8C%96AnnotationAwareAspectJAutoProxyCreator%E7%9B%B8%E5%85%B3%E5%B1%9E%E6%80%A7"><span class="toc-text">Debug调用栈-调用AnnotationAwareAspectJAutoProxyCreator的initBeanFactory()方法初始化AnnotationAwareAspectJAutoProxyCreator相关属性</span></a><ol class="toc-child"><li class="toc-item toc-level-5"><a class="toc-link" href="#%E4%BD%9C%E7%94%A8"><span class="toc-text">作用</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#AbstractAutowireCapableBeanFactory-initializeBean-%E8%BF%9B%E8%A1%8C%E5%88%9D%E5%A7%8B%E5%8C%96"><span class="toc-text">AbstractAutowireCapableBeanFactory#initializeBean()进行初始化</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#AbstractAdvisorAutoProxyCreator-setBeanFactory"><span class="toc-text">AbstractAdvisorAutoProxyCreator#setBeanFactory()</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#AnnotationAwareAspectJAutoProxyCreator-initBeanFactory"><span class="toc-text">AnnotationAwareAspectJAutoProxyCreator#initBeanFactory()</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#AnnotationAwareAspectJAutoProxyCreator%E5%90%8E%E7%BD%AE%E5%A4%84%E7%90%86%E5%99%A8%E5%88%9B%E5%BB%BA%E5%B9%B6%E5%88%9D%E5%A7%8B%E5%8C%96%E5%AE%8C%E6%88%90"><span class="toc-text">AnnotationAwareAspectJAutoProxyCreator后置处理器创建并初始化完成</span></a></li></ol></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#createBean-%E9%87%8C%E8%B0%83%E7%94%A8resolveBeforeInstantiation-%EF%BC%8CAnnotationAwareAspectJAutoProxyCreator%E5%90%8E%E7%BD%AE%E5%A4%84%E7%90%86%E5%99%A8%E5%BC%80%E5%A7%8B%E7%AC%AC%E4%B8%80%E6%AC%A1%E5%8F%91%E6%8C%A5%E4%BD%9C%E7%94%A8"><span class="toc-text">createBean()里调用resolveBeforeInstantiation()，AnnotationAwareAspectJAutoProxyCreator后置处理器开始第一次发挥作用</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#Debug%E8%B0%83%E7%94%A8%E6%A0%88-%E8%B0%83%E7%94%A8AnnotationAwareAspectJAutoProxyCreator%E7%9A%84isInfrastructureClass-%E5%BC%80%E5%A7%8B%E5%8F%82%E4%B8%8E%E5%85%B6%E5%AE%83Bean%E7%9A%84%E5%88%9B%E5%BB%BA%EF%BC%8C%E5%B9%B6%E5%88%A4%E6%96%AD%E5%BD%93%E5%89%8DBean%E6%98%AF%E4%B8%8D%E6%98%AF%E5%88%87%E9%9D%A2"><span class="toc-text">Debug调用栈-调用AnnotationAwareAspectJAutoProxyCreator的isInfrastructureClass()开始参与其它Bean的创建，并判断当前Bean是不是切面</span></a><ol class="toc-child"><li class="toc-item toc-level-5"><a class="toc-link" href="#AbstractAutowireCapableBeanFactory-resolveBeforeInstantiation"><span class="toc-text">AbstractAutowireCapableBeanFactory#resolveBeforeInstantiation()</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#AbstractAutoProxyCreator-postProcessBeforeInstantiation"><span class="toc-text">AbstractAutoProxyCreator#postProcessBeforeInstantiation()</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#AnnotationAwareAspectJAutoProxyCreator-isInfrastructureClass-%E6%89%BE%E5%93%AA%E4%BA%9B%E6%98%AF%E5%88%87%E9%9D%A2"><span class="toc-text">AnnotationAwareAspectJAutoProxyCreator#isInfrastructureClass()找哪些是切面</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#AbstractAutoProxyCreator"><span class="toc-text">AbstractAutoProxyCreator</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#AbstractAspectJAdvisorFactory"><span class="toc-text">AbstractAspectJAdvisorFactory</span></a></li></ol></li><li class="toc-item toc-level-4"><a class="toc-link" href="#Debug%E8%B0%83%E7%94%A8%E6%A0%88-%E8%B0%83%E7%94%A8aspectJAdvisorsBuilder%E7%9A%84findCandidateAdvisors-%E6%96%B9%E6%B3%95"><span class="toc-text">Debug调用栈-调用aspectJAdvisorsBuilder的findCandidateAdvisors()方法</span></a><ol class="toc-child"><li class="toc-item toc-level-5"><a class="toc-link" href="#AspectJAwareAdvisorAutoProxyCreator-shouldSkip"><span class="toc-text">AspectJAwareAdvisorAutoProxyCreator#shouldSkip()</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#AnnotationAwareAspectJAutoProxyCreator-findCandidateAdvisors"><span class="toc-text">AnnotationAwareAspectJAutoProxyCreator#findCandidateAdvisors()</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#BeanFactoryAspectJAdvisorsBuilder-buildAspectJAdvisors-%E6%89%BE%E5%88%B0%E5%88%87%E9%9D%A2%EF%BC%8C%E5%B9%B6%E5%88%9B%E5%BB%BA%E5%A2%9E%E5%BC%BA%E5%99%A8advisors"><span class="toc-text">BeanFactoryAspectJAdvisorsBuilder#buildAspectJAdvisors()找到切面，并创建增强器advisors</span></a></li></ol></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E7%BB%93%E8%AE%BA"><span class="toc-text">结论</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#isInfrastructureClass-%E5%92%8CshouldSkip-%E5%8C%BA%E5%88%AB"><span class="toc-text">isInfrastructureClass()和shouldSkip()区别</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%9E%84%E5%BB%BA%E5%A2%9E%E5%BC%BA%E5%99%A8%E7%9A%84%E8%BF%87%E7%A8%8B"><span class="toc-text">构建增强器的过程</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#BeanactoryAspectJAdvisorsBuilder-buildAspectJAdvisors%E7%9C%9F%E6%AD%A3%E5%BC%80%E5%A7%8B%E6%9E%84%E5%BB%BA%E5%A2%9E%E5%BC%BA%E5%99%A8"><span class="toc-text">BeanactoryAspectJAdvisorsBuilder#buildAspectJAdvisors真正开始构建增强器</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#ReflectiveAspectJAdvisorFactory-getAdvisors-%E6%89%BE%E5%88%B0%E5%88%87%E9%9D%A2%E9%87%8C%E9%9D%A2%E5%AE%9A%E4%B9%89%E7%9A%84%E6%89%80%E6%9C%89%E5%A2%9E%E5%BC%BA%E5%99%A8"><span class="toc-text">ReflectiveAspectJAdvisorFactory#getAdvisors()找到切面里面定义的所有增强器</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#ReflectionUtils"><span class="toc-text">ReflectionUtils</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#ReflectiveAspectJAdvisorFactory-getAdvisor"><span class="toc-text">ReflectiveAspectJAdvisorFactory#getAdvisor()</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#AbstractAspectJAdvisorFactory-1"><span class="toc-text">AbstractAspectJAdvisorFactory</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#createBean-%E9%87%8C%E8%B0%83%E7%94%A8doCreateBean-%EF%BC%8CAnnotationAwareAspectJAutoProxyCreator%E5%BC%80%E5%A7%8B%E7%AC%AC%E4%BA%8C%E6%AC%A1%E5%8F%91%E6%8C%A5%E4%BD%9C%E7%94%A8"><span class="toc-text">createBean()里调用doCreateBean()，AnnotationAwareAspectJAutoProxyCreator开始第二次发挥作用</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#Debug%E8%B0%83%E7%94%A8%E6%A0%88-1"><span class="toc-text">Debug调用栈</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#AnnotationAwareAspectJAutoProxyCreator-findCandidateAdvisors-1"><span class="toc-text">AnnotationAwareAspectJAutoProxyCreator#findCandidateAdvisors()</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#BeanFactoryAspectJAdvisorsBuilder-buildAspectJAdvisors"><span class="toc-text">BeanFactoryAspectJAdvisorsBuilder#buildAspectJAdvisors()</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E7%BB%93%E8%AE%BA-1"><span class="toc-text">结论</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%88%9B%E5%BB%BAHelloService%E4%BB%A3%E7%90%86%E5%AF%B9%E8%B1%A1%E4%B9%8B%E5%89%8D%E7%9A%84%E5%B7%A5%E4%BD%9C"><span class="toc-text">创建HelloService代理对象之前的工作</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%88%9B%E5%BB%BA%E5%AF%B9%E8%B1%A1"><span class="toc-text">创建对象</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E8%B5%8B%E5%80%BC"><span class="toc-text">赋值</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%88%9D%E5%A7%8B%E5%8C%96"><span class="toc-text">初始化</span></a><ol class="toc-child"><li class="toc-item toc-level-5"><a class="toc-link" href="#applyBeanPostProcessorsAfterInitialization%E5%90%8E%E7%BD%AE%E5%88%9D%E5%A7%8B%E5%8C%96%E6%96%B9%E6%B3%95"><span class="toc-text">applyBeanPostProcessorsAfterInitialization后置初始化方法</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#AbstractAutoProxyCreator-postProcessAfterInitialization"><span class="toc-text">AbstractAutoProxyCreator#postProcessAfterInitialization()</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#AbstractAdvisorAutoProxyCreator-findEligibleAdvisors-%E6%98%AF%E5%90%A6%E6%9C%89%E5%88%87%E9%9D%A2%E5%88%87%E5%85%A5%E8%BF%99%E4%B8%AAbean"><span class="toc-text">AbstractAdvisorAutoProxyCreator#findEligibleAdvisors()是否有切面切入这个bean</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#AopUtils-findAdvisorsThatCanApply-%E6%AD%A3%E5%88%99%E8%A7%A3%E6%9E%90%E5%88%87%E9%9D%A2%E8%A1%A8%E8%BE%BE%E5%BC%8F%E5%88%A4%E6%96%AD%E6%98%AF%E5%90%A6%E8%83%BD%E5%88%87%E5%85%A5"><span class="toc-text">AopUtils#findAdvisorsThatCanApply()正则解析切面表达式判断是否能切入</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#%E8%BF%94%E5%9B%9E%E5%88%B0AbstractAdvisorAutoProxyCreator-findEligibleAdvisors"><span class="toc-text">返回到AbstractAdvisorAutoProxyCreator#findEligibleAdvisors()</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#AspectJAwareAdvisorAutoProxyCreator-extendAdvisors"><span class="toc-text">AspectJAwareAdvisorAutoProxyCreator#extendAdvisors()</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#AspectJProxyUtils-makeAdvisorChainAspectJCapableIfNecessary-%E5%88%9B%E5%BB%BA%E5%A2%9E%E5%BC%BA%E5%99%A8%E9%93%BE"><span class="toc-text">AspectJProxyUtils#makeAdvisorChainAspectJCapableIfNecessary()创建增强器链</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#AbstractAutoProxyCreator-createProxy-%E5%BC%80%E5%A7%8B%E5%88%9B%E5%BB%BA%E4%BB%A3%E7%90%86%E5%AF%B9%E8%B1%A1"><span class="toc-text">AbstractAutoProxyCreator#createProxy()开始创建代理对象</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#ProxyFactory-getProxy"><span class="toc-text">ProxyFactory#getProxy()</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#ProxyCreatorSupport-createAopProxy"><span class="toc-text">ProxyCreatorSupport#createAopProxy()</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#DefaultAopProxyFactory-createAopProxy"><span class="toc-text">DefaultAopProxyFactory#createAopProxy()</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#CglibAopProxy-getProxy"><span class="toc-text">CglibAopProxy#getProxy()</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#HelloService%E4%BB%A3%E7%90%86%E5%AF%B9%E8%B1%A1%E5%88%9B%E5%BB%BA%E5%AE%8C%E6%88%90"><span class="toc-text">HelloService代理对象创建完成</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#logAspect%E5%88%9B%E5%BB%BA%E5%8E%9F%E7%94%9F%E5%AF%B9%E8%B1%A1%EF%BC%8C%E8%80%8C%E4%B8%8D%E6%98%AF%E4%BB%A3%E7%90%86%E5%AF%B9%E8%B1%A1"><span class="toc-text">logAspect创建原生对象，而不是代理对象</span></a></li></ol></li></ol></li></ol></li></ol></li></ol></div></div></div></div></main><footer id="footer"><div id="footer-wrap"><div class="copyright">&copy;2020 - 2023 By youthlql</div><div class="framework-info"><span>框架 </span><a target="_blank" rel="noopener" href="https://hexo.io">Hexo</a><span class="footer-separator">|</span><span>主题 </span><a target="_blank" rel="noopener" href="https://github.com/jerryc127/hexo-theme-butterfly">Butterfly</a></div><div class="footer_custom_text"><a href="https://www.upyun.com/?utm_source=lianmeng&utm_medium=referral" target="_blank" rel="noopener" class="one-pan-link-mark"><img style="position:relative;top:-3px; " src= "" data-lazy-src="https://npm.elemecdn.com/lql_static@latest/upyun/logo.png" align="absmiddle" width="60px" height="30px"></a><a target="_blank" rel="noopener" href="https://beian.miit.gov.cn"><img class="icp-icon" src= "" data-lazy-src="https://npm.elemecdn.com/lql_static@latest/logo/icp.png"><span>鄂ICP备19028890号</span></a></div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="translateLink" type="button" title="简繁转换">简</button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><button id="go-up" type="button" title="回到顶部"><i class="fas fa-arrow-up"></i></button></div></div><div id="local-search"><div class="search-dialog"><nav class="search-nav"><span class="search-dialog-title">本地搜索</span><span id="loading-status"></span><button class="search-close-button"><i class="fas fa-times"></i></button></nav><div class="is-center" id="loading-database"><i class="fas fa-spinner fa-pulse"></i><span>  数据库加载中</span></div><div class="search-wrap"><div id="local-search-input"><div class="local-search-box"><input class="local-search-box--input" placeholder="搜索文章" type="text"/></div></div><hr/><div id="local-search-results"></div></div></div><div id="search-mask"></div></div><div><script src="/js/utils.js"></script><script src="/js/main.js"></script><script src="/js/tw_cn.js"></script><script src="https://npm.elemecdn.com/@fancyapps/ui/dist/fancybox.umd.js"></script><script src="https://npm.elemecdn.com/instant.page/instantpage.js" type="module"></script><script src="https://cdn.jsdelivr.net/npm/vanilla-lazyload/dist/lazyload.iife.min.js"></script><script src="/js/search/local-search.js"></script><div class="js-pjax"></div><script defer src="https://npm.elemecdn.com/jquery@latest/dist/jquery.min.js"></script></div></body></html>